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