remove typo
[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 "IntrinsicEmitter.h"
15 #include "Record.h"
16 #include "llvm/ADT/StringExtras.h"
17 using namespace llvm;
18
19 //===----------------------------------------------------------------------===//
20 // CodeGenIntrinsic Implementation
21 //===----------------------------------------------------------------------===//
22
23 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC) {
24   std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
25   return std::vector<CodeGenIntrinsic>(I.begin(), I.end());
26 }
27
28 CodeGenIntrinsic::CodeGenIntrinsic(Record *R) {
29   std::string DefName = R->getName();
30   ModRef = WriteMem;
31   
32   if (DefName.size() <= 4 || 
33       std::string(DefName.begin(), DefName.begin()+4) != "int_")
34     throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
35   EnumName = std::string(DefName.begin()+4, DefName.end());
36   GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
37   TargetPrefix   = R->getValueAsString("TargetPrefix");
38   Name = R->getValueAsString("LLVMName");
39   if (Name == "") {
40     // If an explicit name isn't specified, derive one from the DefName.
41     Name = "llvm.";
42     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
43       if (EnumName[i] == '_')
44         Name += '.';
45       else
46         Name += EnumName[i];
47   } else {
48     // Verify it starts with "llvm.".
49     if (Name.size() <= 5 || 
50         std::string(Name.begin(), Name.begin()+5) != "llvm.")
51       throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
52   }
53   
54   // If TargetPrefix is specified, make sure that Name starts with
55   // "llvm.<targetprefix>.".
56   if (!TargetPrefix.empty()) {
57     if (Name.size() < 6+TargetPrefix.size() ||
58         std::string(Name.begin()+5, Name.begin()+6+TargetPrefix.size()) 
59           != (TargetPrefix+"."))
60       throw "Intrinsic '" + DefName + "' does not start with 'llvm." + 
61             TargetPrefix + ".'!";
62   }
63   
64   // Parse the list of argument types.
65   ListInit *TypeList = R->getValueAsListInit("Types");
66   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
67     DefInit *DI = dynamic_cast<DefInit*>(TypeList->getElement(i));
68     assert(DI && "Invalid list type!");
69     Record *TyEl = DI->getDef();
70     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
71     ArgTypes.push_back(TyEl->getValueAsString("TypeVal"));
72     ArgTypeDefs.push_back(TyEl);
73   }
74   if (ArgTypes.size() == 0)
75     throw "Intrinsic '"+DefName+"' needs at least a type for the ret value!";
76   
77   // Parse the intrinsic properties.
78   ListInit *PropList = R->getValueAsListInit("Properties");
79   for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
80     DefInit *DI = dynamic_cast<DefInit*>(PropList->getElement(i));
81     assert(DI && "Invalid list type!");
82     Record *Property = DI->getDef();
83     assert(Property->isSubClassOf("IntrinsicProperty") &&
84            "Expected a property!");
85
86     if (Property->getName() == "InstrNoMem")
87       ModRef = NoMem;
88     else if (Property->getName() == "InstrReadArgMem")
89       ModRef = ReadArgMem;
90     else if (Property->getName() == "IntrReadMem")
91       ModRef = ReadMem;
92     else if (Property->getName() == "InstrWriteArgMem")
93       ModRef = WriteArgMem;
94     else if (Property->getName() == "IntrWriteMem")
95       ModRef = WriteMem;
96     else
97       assert(0 && "Unknown property!");
98   }
99 }
100
101 //===----------------------------------------------------------------------===//
102 // IntrinsicEmitter Implementation
103 //===----------------------------------------------------------------------===//
104
105 void IntrinsicEmitter::run(std::ostream &OS) {
106   EmitSourceFileHeader("Intrinsic Function Source Fragment", OS);
107   
108   std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records);
109
110   // Emit the enum information.
111   EmitEnumInfo(Ints, OS);
112
113   // Emit the intrinsic ID -> name table.
114   EmitIntrinsicToNameTable(Ints, OS);
115   
116   // Emit the function name recognizer.
117   EmitFnNameRecognizer(Ints, OS);
118   
119   // Emit the intrinsic verifier.
120   EmitVerifier(Ints, OS);
121   
122   // Emit mod/ref info for each function.
123   EmitModRefInfo(Ints, OS);
124   
125   // Emit side effect info for each function.
126   EmitSideEffectInfo(Ints, OS);
127
128   // Emit a list of intrinsics with corresponding GCC builtins.
129   EmitGCCBuiltinList(Ints, OS);
130
131   // Emit code to translate GCC builtins into LLVM intrinsics.
132   EmitIntrinsicToGCCBuiltinMap(Ints, OS);
133 }
134
135 void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
136                                     std::ostream &OS) {
137   OS << "// Enum values for Intrinsics.h\n";
138   OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
139   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
140     OS << "    " << Ints[i].EnumName;
141     OS << ((i != e-1) ? ", " : "  ");
142     OS << std::string(40-Ints[i].EnumName.size(), ' ') 
143       << "// " << Ints[i].Name << "\n";
144   }
145   OS << "#endif\n\n";
146 }
147
148 void IntrinsicEmitter::
149 EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints, 
150                      std::ostream &OS) {
151   // Build a function name -> intrinsic name mapping.
152   std::map<std::string, std::string> IntMapping;
153   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
154     IntMapping[Ints[i].Name] = Ints[i].EnumName;
155     
156   OS << "// Function name -> enum value recognizer code.\n";
157   OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
158   OS << "  switch (Name[5]) {\n";
159   OS << "  default: break;\n";
160   // Emit the intrinsics in sorted order.
161   char LastChar = 0;
162   for (std::map<std::string, std::string>::iterator I = IntMapping.begin(),
163        E = IntMapping.end(); I != E; ++I) {
164     if (I->first[5] != LastChar) {
165       LastChar = I->first[5];
166       OS << "  case '" << LastChar << "':\n";
167     }
168     
169     OS << "    if (Name == \"" << I->first << "\") return Intrinsic::"
170        << I->second << ";\n";
171   }
172   OS << "  }\n";
173   OS << "  // The 'llvm.' namespace is reserved!\n";
174   OS << "  assert(0 && \"Unknown LLVM intrinsic function!\");\n";
175   OS << "#endif\n\n";
176 }
177
178 void IntrinsicEmitter::
179 EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints, 
180                          std::ostream &OS) {
181   std::vector<std::string> Names;
182   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
183     Names.push_back(Ints[i].Name);
184   std::sort(Names.begin(), Names.end());
185   
186   OS << "// Intrinsic ID to name table\n";
187   OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
188   OS << "  // Note that entry #0 is the invalid intrinsic!\n";
189   for (unsigned i = 0, e = Names.size(); i != e; ++i)
190     OS << "  \"" << Names[i] << "\",\n";
191   OS << "#endif\n\n";
192 }
193
194 static void EmitTypeVerify(std::ostream &OS, const std::string &Val,
195                            Record *ArgType) {
196   OS << "    Assert1(" << Val << "->getTypeID() == "
197      << ArgType->getValueAsString("TypeVal") << ",\n"
198      << "            \"Illegal intrinsic type!\", IF);\n";
199
200   // If this is a packed type, check that the subtype and size are correct.
201   if (ArgType->isSubClassOf("LLVMPackedType")) {
202     Record *SubType = ArgType->getValueAsDef("ElTy");
203     OS << "    Assert1(cast<PackedType>(" << Val
204        << ")->getElementType()->getTypeID() == "
205        << SubType->getValueAsString("TypeVal") << ",\n"
206        << "            \"Illegal intrinsic type!\", IF);\n";
207     OS << "    Assert1(cast<PackedType>(" << Val << ")->getNumElements() == "
208        << ArgType->getValueAsInt("NumElts") << ",\n"
209        << "            \"Illegal intrinsic type!\", IF);\n";
210   }
211 }
212
213 void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints, 
214                                     std::ostream &OS) {
215   OS << "// Verifier::visitIntrinsicFunctionCall code.\n";
216   OS << "#ifdef GET_INTRINSIC_VERIFIER\n";
217   OS << "  switch (ID) {\n";
218   OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
219   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
220     OS << "  case Intrinsic::" << Ints[i].EnumName << ":\t\t// "
221        << Ints[i].Name << "\n";
222     OS << "    Assert1(FTy->getNumParams() == " << Ints[i].ArgTypes.size()-1
223        << ",\n"
224        << "            \"Illegal # arguments for intrinsic function!\", IF);\n";
225     EmitTypeVerify(OS, "FTy->getReturnType()", Ints[i].ArgTypeDefs[0]);
226     for (unsigned j = 1; j != Ints[i].ArgTypes.size(); ++j)
227       EmitTypeVerify(OS, "FTy->getParamType(" + utostr(j-1) + ")",
228                      Ints[i].ArgTypeDefs[j]);
229     OS << "    break;\n";
230   }
231   OS << "  }\n";
232   OS << "#endif\n\n";
233 }
234
235 void IntrinsicEmitter::EmitModRefInfo(const std::vector<CodeGenIntrinsic> &Ints,
236                                       std::ostream &OS) {
237   OS << "// BasicAliasAnalysis code.\n";
238   OS << "#ifdef GET_MODREF_BEHAVIOR\n";
239   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
240     switch (Ints[i].ModRef) {
241     default: break;
242     case CodeGenIntrinsic::NoMem:
243       OS << "  NoMemoryTable.push_back(\"" << Ints[i].Name << "\");\n";
244       break;
245     case CodeGenIntrinsic::ReadArgMem:
246     case CodeGenIntrinsic::ReadMem:
247       OS << "  OnlyReadsMemoryTable.push_back(\"" << Ints[i].Name << "\");\n";
248       break;
249     }
250   }
251   OS << "#endif\n\n";
252 }
253
254 void IntrinsicEmitter::
255 EmitSideEffectInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){
256   OS << "// isInstructionTriviallyDead code.\n";
257   OS << "#ifdef GET_SIDE_EFFECT_INFO\n";
258   OS << "  switch (F->getIntrinsicID()) {\n";
259   OS << "  default: break;\n";
260   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
261     switch (Ints[i].ModRef) {
262     default: break;
263     case CodeGenIntrinsic::NoMem:
264     case CodeGenIntrinsic::ReadArgMem:
265     case CodeGenIntrinsic::ReadMem:
266       OS << "  case Intrinsic::" << Ints[i].EnumName << ":\n";
267       break;
268     }
269   }
270   OS << "    return true; // These intrinsics have no side effects.\n";
271   OS << "  }\n";
272   OS << "#endif\n\n";
273 }
274
275 void IntrinsicEmitter::
276 EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){
277   OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n";
278   OS << "#ifdef GET_GCC_BUILTIN_NAME\n";
279   OS << "  switch (F->getIntrinsicID()) {\n";
280   OS << "  default: BuiltinName = \"\"; break;\n";
281   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
282     if (!Ints[i].GCCBuiltinName.empty()) {
283       OS << "  case Intrinsic::" << Ints[i].EnumName << ": BuiltinName = \""
284          << Ints[i].GCCBuiltinName << "\"; break;\n";
285     }
286   }
287   OS << "  }\n";
288   OS << "#endif\n\n";
289 }
290
291 void IntrinsicEmitter::
292 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, 
293                              std::ostream &OS) {
294   typedef std::map<std::pair<std::string, std::string>, std::string> BIMTy;
295   BIMTy BuiltinMap;
296   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
297     if (!Ints[i].GCCBuiltinName.empty()) {
298       std::pair<std::string, std::string> Key(Ints[i].GCCBuiltinName,
299                                               Ints[i].TargetPrefix);
300       if (!BuiltinMap.insert(std::make_pair(Key, Ints[i].EnumName)).second)
301         throw "Intrinsic '" + Ints[i].TheDef->getName() +
302               "': duplicate GCC builtin name!";
303     }
304   }
305   
306   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
307   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
308   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
309   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
310   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
311   OS << "  if (0);\n";
312   // Note: this could emit significantly better code if we cared.
313   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
314     OS << "  else if (";
315     if (!I->first.second.empty()) {
316       // Emit this as a strcmp, so it can be constant folded by the FE.
317       OS << "!strcmp(TargetPrefix, \"" << I->first.second << "\") &&\n"
318          << "           ";
319     }
320     OS << "!strcmp(BuiltinName, \"" << I->first.first << "\"))\n";
321     OS << "    IntrinsicID = Intrinsic::" << I->second << ";\n";
322   }
323   OS << "  else\n";
324   OS << "    IntrinsicID = Intrinsic::not_intrinsic;\n";
325   OS << "#endif\n\n";
326 }