blob: 0438a7e5d69df68f2ce2288de62ed5c9bb98a8df [file] [log] [blame]
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001//===-- CppWriter.cpp - Printing LLVM IR as a C++ Source File -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Reid Spencere0d133f2006-05-29 18:08:06 +00005// This file was developed by Reid Spencer and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the writing of the LLVM IR as a set of C++ calls to the
11// LLVM IR interface. The input module is assumed to be verified.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/CallingConv.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/InlineAsm.h"
19#include "llvm/Instruction.h"
20#include "llvm/Instructions.h"
21#include "llvm/Module.h"
22#include "llvm/SymbolTable.h"
23#include "llvm/Support/CFG.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/MathExtras.h"
Reid Spencer15f7e012006-05-30 21:18:23 +000027#include "llvm/Support/CommandLine.h"
Reid Spencerf977e7b2006-06-01 23:43:47 +000028#include "llvm/Config/config.h"
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000029#include <algorithm>
30#include <iostream>
Reid Spencer66c87342006-05-30 03:43:49 +000031#include <set>
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000032
33using namespace llvm;
34
Reid Spencer15f7e012006-05-30 21:18:23 +000035static cl::opt<std::string>
Reid Spencer15f7e012006-05-30 21:18:23 +000036FuncName("funcname", cl::desc("Specify the name of the generated function"),
37 cl::value_desc("function name"));
38
Reid Spencer12803f52006-05-31 17:31:38 +000039enum WhatToGenerate {
40 GenProgram,
41 GenModule,
42 GenContents,
43 GenFunction,
Reid Spencerf977e7b2006-06-01 23:43:47 +000044 GenInline,
Reid Spencer12803f52006-05-31 17:31:38 +000045 GenVariable,
46 GenType
47};
48
49static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
50 cl::desc("Choose what kind of output to generate"),
51 cl::init(GenProgram),
52 cl::values(
53 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
54 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
55 clEnumValN(GenContents,"gen-contents", "Generate contents of a module"),
56 clEnumValN(GenFunction,"gen-function", "Generate a function definition"),
Reid Spencerf977e7b2006-06-01 23:43:47 +000057 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
Reid Spencer12803f52006-05-31 17:31:38 +000058 clEnumValN(GenVariable,"gen-variable", "Generate a variable definition"),
59 clEnumValN(GenType, "gen-type", "Generate a type definition"),
60 clEnumValEnd
61 )
62);
63
64static cl::opt<std::string> NameToGenerate("for", cl::Optional,
65 cl::desc("Specify the name of the thing to generate"),
66 cl::init("!bad!"));
Reid Spencer15f7e012006-05-30 21:18:23 +000067
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000068namespace {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000069typedef std::vector<const Type*> TypeList;
70typedef std::map<const Type*,std::string> TypeMap;
71typedef std::map<const Value*,std::string> ValueMap;
Reid Spencer66c87342006-05-30 03:43:49 +000072typedef std::set<std::string> NameSet;
Reid Spencer15f7e012006-05-30 21:18:23 +000073typedef std::set<const Type*> TypeSet;
74typedef std::set<const Value*> ValueSet;
75typedef std::map<const Value*,std::string> ForwardRefMap;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000076
Reid Spencere0d133f2006-05-29 18:08:06 +000077class CppWriter {
Reid Spencer12803f52006-05-31 17:31:38 +000078 const char* progname;
Reid Spencere0d133f2006-05-29 18:08:06 +000079 std::ostream &Out;
80 const Module *TheModule;
Andrew Lenharth539d8712006-05-31 20:18:56 +000081 uint64_t uniqueNum;
Reid Spencere0d133f2006-05-29 18:08:06 +000082 TypeMap TypeNames;
83 ValueMap ValueNames;
84 TypeMap UnresolvedTypes;
85 TypeList TypeStack;
Reid Spencer66c87342006-05-30 03:43:49 +000086 NameSet UsedNames;
Reid Spencer15f7e012006-05-30 21:18:23 +000087 TypeSet DefinedTypes;
88 ValueSet DefinedValues;
89 ForwardRefMap ForwardRefs;
Reid Spencerf977e7b2006-06-01 23:43:47 +000090 bool is_inline;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000091
Reid Spencere0d133f2006-05-29 18:08:06 +000092public:
Reid Spencer12803f52006-05-31 17:31:38 +000093 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
94 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
Reid Spencerf977e7b2006-06-01 23:43:47 +000095 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000096
Reid Spencere0d133f2006-05-29 18:08:06 +000097 const Module* getModule() { return TheModule; }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +000098
Reid Spencer12803f52006-05-31 17:31:38 +000099 void printProgram(const std::string& fname, const std::string& modName );
100 void printModule(const std::string& fname, const std::string& modName );
101 void printContents(const std::string& fname, const std::string& modName );
102 void printFunction(const std::string& fname, const std::string& funcName );
Reid Spencerf977e7b2006-06-01 23:43:47 +0000103 void printInline(const std::string& fname, const std::string& funcName );
Reid Spencer12803f52006-05-31 17:31:38 +0000104 void printVariable(const std::string& fname, const std::string& varName );
105 void printType(const std::string& fname, const std::string& typeName );
106
107 void error(const std::string& msg);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000108
Reid Spencere0d133f2006-05-29 18:08:06 +0000109private:
Reid Spencer12803f52006-05-31 17:31:38 +0000110 void printLinkageType(GlobalValue::LinkageTypes LT);
111 void printCallingConv(unsigned cc);
112 void printEscapedString(const std::string& str);
113 void printCFP(const ConstantFP* CFP);
114
115 std::string getCppName(const Type* val);
116 inline void printCppName(const Type* val);
117
118 std::string getCppName(const Value* val);
119 inline void printCppName(const Value* val);
120
121 bool printTypeInternal(const Type* Ty);
122 inline void printType(const Type* Ty);
Reid Spencere0d133f2006-05-29 18:08:06 +0000123 void printTypes(const Module* M);
Reid Spencer12803f52006-05-31 17:31:38 +0000124
Reid Spencere0d133f2006-05-29 18:08:06 +0000125 void printConstant(const Constant *CPV);
Reid Spencer12803f52006-05-31 17:31:38 +0000126 void printConstants(const Module* M);
127
128 void printVariableUses(const GlobalVariable *GV);
129 void printVariableHead(const GlobalVariable *GV);
130 void printVariableBody(const GlobalVariable *GV);
131
132 void printFunctionUses(const Function *F);
Reid Spencer66c87342006-05-30 03:43:49 +0000133 void printFunctionHead(const Function *F);
134 void printFunctionBody(const Function *F);
Reid Spencere0d133f2006-05-29 18:08:06 +0000135 void printInstruction(const Instruction *I, const std::string& bbname);
Reid Spencer15f7e012006-05-30 21:18:23 +0000136 std::string getOpName(Value*);
137
Reid Spencer12803f52006-05-31 17:31:38 +0000138 void printModuleBody();
139
Reid Spencere0d133f2006-05-29 18:08:06 +0000140};
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000141
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000142static unsigned indent_level = 0;
143inline std::ostream& nl(std::ostream& Out, int delta = 0) {
144 Out << "\n";
145 if (delta >= 0 || indent_level >= unsigned(-delta))
146 indent_level += delta;
147 for (unsigned i = 0; i < indent_level; ++i)
148 Out << " ";
149 return Out;
150}
151
152inline void in() { indent_level++; }
153inline void out() { if (indent_level >0) indent_level--; }
154
Reid Spencer12803f52006-05-31 17:31:38 +0000155inline void
156sanitize(std::string& str) {
157 for (size_t i = 0; i < str.length(); ++i)
158 if (!isalnum(str[i]) && str[i] != '_')
159 str[i] = '_';
160}
161
162inline const char*
163getTypePrefix(const Type* Ty ) {
164 const char* prefix;
165 switch (Ty->getTypeID()) {
166 case Type::VoidTyID: prefix = "void_"; break;
167 case Type::BoolTyID: prefix = "bool_"; break;
168 case Type::UByteTyID: prefix = "ubyte_"; break;
169 case Type::SByteTyID: prefix = "sbyte_"; break;
170 case Type::UShortTyID: prefix = "ushort_"; break;
171 case Type::ShortTyID: prefix = "short_"; break;
172 case Type::UIntTyID: prefix = "uint_"; break;
173 case Type::IntTyID: prefix = "int_"; break;
174 case Type::ULongTyID: prefix = "ulong_"; break;
175 case Type::LongTyID: prefix = "long_"; break;
176 case Type::FloatTyID: prefix = "float_"; break;
177 case Type::DoubleTyID: prefix = "double_"; break;
178 case Type::LabelTyID: prefix = "label_"; break;
179 case Type::FunctionTyID: prefix = "func_"; break;
180 case Type::StructTyID: prefix = "struct_"; break;
181 case Type::ArrayTyID: prefix = "array_"; break;
182 case Type::PointerTyID: prefix = "ptr_"; break;
183 case Type::PackedTyID: prefix = "packed_"; break;
184 case Type::OpaqueTyID: prefix = "opaque_"; break;
185 default: prefix = "other_"; break;
186 }
187 return prefix;
188}
189
190// Looks up the type in the symbol table and returns a pointer to its name or
191// a null pointer if it wasn't found. Note that this isn't the same as the
192// Mode::getTypeName function which will return an empty string, not a null
193// pointer if the name is not found.
194inline const std::string*
195findTypeName(const SymbolTable& ST, const Type* Ty)
196{
197 SymbolTable::type_const_iterator TI = ST.type_begin();
198 SymbolTable::type_const_iterator TE = ST.type_end();
199 for (;TI != TE; ++TI)
200 if (TI->second == Ty)
201 return &(TI->first);
202 return 0;
203}
204
205void
206CppWriter::error(const std::string& msg) {
207 std::cerr << progname << ": " << msg << "\n";
208 exit(2);
209}
210
Reid Spencer15f7e012006-05-30 21:18:23 +0000211// printCFP - Print a floating point constant .. very carefully :)
212// This makes sure that conversion to/from floating yields the same binary
213// result so that we don't lose precision.
214void
215CppWriter::printCFP(const ConstantFP *CFP) {
Reid Spencerf977e7b2006-06-01 23:43:47 +0000216 Out << "ConstantFP::get(";
217 if (CFP->getType() == Type::DoubleTy)
218 Out << "Type::DoubleTy, ";
219 else
220 Out << "Type::FloatTy, ";
Reid Spencer15f7e012006-05-30 21:18:23 +0000221#if HAVE_PRINTF_A
222 char Buffer[100];
223 sprintf(Buffer, "%A", CFP->getValue());
224 if ((!strncmp(Buffer, "0x", 2) ||
225 !strncmp(Buffer, "-0x", 3) ||
226 !strncmp(Buffer, "+0x", 3)) &&
227 (atof(Buffer) == CFP->getValue()))
Reid Spencerf977e7b2006-06-01 23:43:47 +0000228 if (CFP->getType() == Type::DoubleTy)
229 Out << "BitsToDouble(" << Buffer << ")";
230 else
231 Out << "BitsToFloat(" << Buffer << ")";
Reid Spencer15f7e012006-05-30 21:18:23 +0000232 else {
Reid Spencer15f7e012006-05-30 21:18:23 +0000233#endif
Reid Spencerf977e7b2006-06-01 23:43:47 +0000234 std::string StrVal = ftostr(CFP->getValue());
235
236 while (StrVal[0] == ' ')
237 StrVal.erase(StrVal.begin());
238
239 // Check to make sure that the stringized number is not some string like
240 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
241 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
242 ((StrVal[0] == '-' || StrVal[0] == '+') &&
243 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
244 (atof(StrVal.c_str()) == CFP->getValue()))
245 if (CFP->getType() == Type::DoubleTy)
246 Out << StrVal;
247 else
248 Out << StrVal;
249 else if (CFP->getType() == Type::DoubleTy)
250 Out << "BitsToDouble(0x" << std::hex << DoubleToBits(CFP->getValue())
251 << std::dec << "ULL) /* " << StrVal << " */";
252 else
253 Out << "BitsToFloat(0x" << std::hex << FloatToBits(CFP->getValue())
254 << std::dec << "U) /* " << StrVal << " */";
Reid Spencer15f7e012006-05-30 21:18:23 +0000255#if HAVE_PRINTF_A
256 }
257#endif
Reid Spencerf977e7b2006-06-01 23:43:47 +0000258 Out << ")";
Reid Spencer15f7e012006-05-30 21:18:23 +0000259}
260
Reid Spencer12803f52006-05-31 17:31:38 +0000261void
262CppWriter::printCallingConv(unsigned cc){
263 // Print the calling convention.
264 switch (cc) {
265 case CallingConv::C: Out << "CallingConv::C"; break;
266 case CallingConv::CSRet: Out << "CallingConv::CSRet"; break;
267 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
268 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
269 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
270 default: Out << cc; break;
271 }
272}
Reid Spencer15f7e012006-05-30 21:18:23 +0000273
Reid Spencer12803f52006-05-31 17:31:38 +0000274void
275CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
276 switch (LT) {
277 case GlobalValue::InternalLinkage:
278 Out << "GlobalValue::InternalLinkage"; break;
279 case GlobalValue::LinkOnceLinkage:
280 Out << "GlobalValue::LinkOnceLinkage "; break;
281 case GlobalValue::WeakLinkage:
282 Out << "GlobalValue::WeakLinkage"; break;
283 case GlobalValue::AppendingLinkage:
284 Out << "GlobalValue::AppendingLinkage"; break;
285 case GlobalValue::ExternalLinkage:
286 Out << "GlobalValue::ExternalLinkage"; break;
287 case GlobalValue::GhostLinkage:
288 Out << "GlobalValue::GhostLinkage"; break;
289 }
Reid Spencer15f7e012006-05-30 21:18:23 +0000290}
291
Reid Spencere0d133f2006-05-29 18:08:06 +0000292// printEscapedString - Print each character of the specified string, escaping
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000293// it if it is not printable or if it is an escape char.
Reid Spencere0d133f2006-05-29 18:08:06 +0000294void
295CppWriter::printEscapedString(const std::string &Str) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000296 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
297 unsigned char C = Str[i];
298 if (isprint(C) && C != '"' && C != '\\') {
299 Out << C;
300 } else {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000301 Out << "\\x"
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000302 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
303 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
304 }
305 }
306}
307
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000308std::string
309CppWriter::getCppName(const Type* Ty)
310{
311 // First, handle the primitive types .. easy
312 if (Ty->isPrimitiveType()) {
313 switch (Ty->getTypeID()) {
314 case Type::VoidTyID: return "Type::VoidTy";
315 case Type::BoolTyID: return "Type::BoolTy";
316 case Type::UByteTyID: return "Type::UByteTy";
317 case Type::SByteTyID: return "Type::SByteTy";
318 case Type::UShortTyID: return "Type::UShortTy";
319 case Type::ShortTyID: return "Type::ShortTy";
320 case Type::UIntTyID: return "Type::UIntTy";
321 case Type::IntTyID: return "Type::IntTy";
322 case Type::ULongTyID: return "Type::ULongTy";
323 case Type::LongTyID: return "Type::LongTy";
324 case Type::FloatTyID: return "Type::FloatTy";
325 case Type::DoubleTyID: return "Type::DoubleTy";
326 case Type::LabelTyID: return "Type::LabelTy";
327 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000328 error("Invalid primitive type");
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000329 break;
330 }
331 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
332 }
333
334 // Now, see if we've seen the type before and return that
335 TypeMap::iterator I = TypeNames.find(Ty);
336 if (I != TypeNames.end())
337 return I->second;
338
339 // Okay, let's build a new name for this type. Start with a prefix
340 const char* prefix = 0;
341 switch (Ty->getTypeID()) {
342 case Type::FunctionTyID: prefix = "FuncTy_"; break;
343 case Type::StructTyID: prefix = "StructTy_"; break;
344 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
345 case Type::PointerTyID: prefix = "PointerTy_"; break;
346 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
347 case Type::PackedTyID: prefix = "PackedTy_"; break;
348 default: prefix = "OtherTy_"; break; // prevent breakage
349 }
350
351 // See if the type has a name in the symboltable and build accordingly
352 const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
353 std::string name;
354 if (tName)
355 name = std::string(prefix) + *tName;
356 else
357 name = std::string(prefix) + utostr(uniqueNum++);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000358 sanitize(name);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000359
360 // Save the name
361 return TypeNames[Ty] = name;
362}
363
Reid Spencer12803f52006-05-31 17:31:38 +0000364void
365CppWriter::printCppName(const Type* Ty)
366{
367 printEscapedString(getCppName(Ty));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000368}
369
Reid Spencer12803f52006-05-31 17:31:38 +0000370std::string
371CppWriter::getCppName(const Value* val) {
372 std::string name;
373 ValueMap::iterator I = ValueNames.find(val);
374 if (I != ValueNames.end() && I->first == val)
375 return I->second;
Reid Spencer25edc352006-05-31 04:43:19 +0000376
Reid Spencer12803f52006-05-31 17:31:38 +0000377 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
378 name = std::string("gvar_") +
379 getTypePrefix(GV->getType()->getElementType());
380 } else if (const Function* F = dyn_cast<Function>(val)) {
381 name = std::string("func_");
382 } else if (const Constant* C = dyn_cast<Constant>(val)) {
383 name = std::string("const_") + getTypePrefix(C->getType());
Reid Spencerf977e7b2006-06-01 23:43:47 +0000384 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
385 if (is_inline) {
386 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
387 Function::const_arg_iterator(Arg)) + 1;
388 name = std::string("arg_") + utostr(argNum);
389 NameSet::iterator NI = UsedNames.find(name);
390 if (NI != UsedNames.end())
391 name += std::string("_") + utostr(uniqueNum++);
392 UsedNames.insert(name);
393 return ValueNames[val] = name;
394 } else {
395 name = getTypePrefix(val->getType());
396 }
Reid Spencer12803f52006-05-31 17:31:38 +0000397 } else {
398 name = getTypePrefix(val->getType());
Reid Spencer25edc352006-05-31 04:43:19 +0000399 }
Reid Spencer12803f52006-05-31 17:31:38 +0000400 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
401 sanitize(name);
402 NameSet::iterator NI = UsedNames.find(name);
403 if (NI != UsedNames.end())
404 name += std::string("_") + utostr(uniqueNum++);
405 UsedNames.insert(name);
406 return ValueNames[val] = name;
Reid Spencer25edc352006-05-31 04:43:19 +0000407}
408
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000409void
Reid Spencer12803f52006-05-31 17:31:38 +0000410CppWriter::printCppName(const Value* val) {
411 printEscapedString(getCppName(val));
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000412}
413
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000414bool
Reid Spencer12803f52006-05-31 17:31:38 +0000415CppWriter::printTypeInternal(const Type* Ty) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000416 // We don't print definitions for primitive types
417 if (Ty->isPrimitiveType())
418 return false;
419
Reid Spencer15f7e012006-05-30 21:18:23 +0000420 // If we already defined this type, we don't need to define it again.
421 if (DefinedTypes.find(Ty) != DefinedTypes.end())
422 return false;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000423
Reid Spencer15f7e012006-05-30 21:18:23 +0000424 // Everything below needs the name for the type so get it now.
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000425 std::string typeName(getCppName(Ty));
426
427 // Search the type stack for recursion. If we find it, then generate this
428 // as an OpaqueType, but make sure not to do this multiple times because
429 // the type could appear in multiple places on the stack. Once the opaque
Reid Spencer15f7e012006-05-30 21:18:23 +0000430 // definition is issued, it must not be re-issued. Consequently we have to
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000431 // check the UnresolvedTypes list as well.
Reid Spencer12803f52006-05-31 17:31:38 +0000432 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
433 if (TI != TypeStack.end()) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000434 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
435 if (I == UnresolvedTypes.end()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000436 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
437 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000438 UnresolvedTypes[Ty] = typeName;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000439 }
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000440 return true;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000441 }
442
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000443 // We're going to print a derived type which, by definition, contains other
444 // types. So, push this one we're printing onto the type stack to assist with
445 // recursive definitions.
Reid Spencer15f7e012006-05-30 21:18:23 +0000446 TypeStack.push_back(Ty);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000447
448 // Print the type definition
449 switch (Ty->getTypeID()) {
450 case Type::FunctionTyID: {
451 const FunctionType* FT = cast<FunctionType>(Ty);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000452 Out << "std::vector<const Type*>" << typeName << "_args;";
453 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000454 FunctionType::param_iterator PI = FT->param_begin();
455 FunctionType::param_iterator PE = FT->param_end();
456 for (; PI != PE; ++PI) {
457 const Type* argTy = static_cast<const Type*>(*PI);
Reid Spencer12803f52006-05-31 17:31:38 +0000458 bool isForward = printTypeInternal(argTy);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000459 std::string argName(getCppName(argTy));
460 Out << typeName << "_args.push_back(" << argName;
461 if (isForward)
462 Out << "_fwd";
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000463 Out << ");";
464 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000465 }
Reid Spencer12803f52006-05-31 17:31:38 +0000466 bool isForward = printTypeInternal(FT->getReturnType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000467 std::string retTypeName(getCppName(FT->getReturnType()));
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000468 Out << "FunctionType* " << typeName << " = FunctionType::get(";
469 in(); nl(Out) << "/*Result=*/" << retTypeName;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000470 if (isForward)
471 Out << "_fwd";
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000472 Out << ",";
473 nl(Out) << "/*Params=*/" << typeName << "_args,";
474 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
475 out();
476 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000477 break;
478 }
479 case Type::StructTyID: {
480 const StructType* ST = cast<StructType>(Ty);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000481 Out << "std::vector<const Type*>" << typeName << "_fields;";
482 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000483 StructType::element_iterator EI = ST->element_begin();
484 StructType::element_iterator EE = ST->element_end();
485 for (; EI != EE; ++EI) {
486 const Type* fieldTy = static_cast<const Type*>(*EI);
Reid Spencer12803f52006-05-31 17:31:38 +0000487 bool isForward = printTypeInternal(fieldTy);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000488 std::string fieldName(getCppName(fieldTy));
489 Out << typeName << "_fields.push_back(" << fieldName;
490 if (isForward)
491 Out << "_fwd";
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000492 Out << ");";
493 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000494 }
495 Out << "StructType* " << typeName << " = StructType::get("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000496 << typeName << "_fields);";
497 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000498 break;
499 }
500 case Type::ArrayTyID: {
501 const ArrayType* AT = cast<ArrayType>(Ty);
502 const Type* ET = AT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000503 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000504 std::string elemName(getCppName(ET));
505 Out << "ArrayType* " << typeName << " = ArrayType::get("
506 << elemName << (isForward ? "_fwd" : "")
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000507 << ", " << utostr(AT->getNumElements()) << ");";
508 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000509 break;
510 }
511 case Type::PointerTyID: {
512 const PointerType* PT = cast<PointerType>(Ty);
513 const Type* ET = PT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000514 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000515 std::string elemName(getCppName(ET));
516 Out << "PointerType* " << typeName << " = PointerType::get("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000517 << elemName << (isForward ? "_fwd" : "") << ");";
518 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000519 break;
520 }
521 case Type::PackedTyID: {
522 const PackedType* PT = cast<PackedType>(Ty);
523 const Type* ET = PT->getElementType();
Reid Spencer12803f52006-05-31 17:31:38 +0000524 bool isForward = printTypeInternal(ET);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000525 std::string elemName(getCppName(ET));
526 Out << "PackedType* " << typeName << " = PackedType::get("
527 << elemName << (isForward ? "_fwd" : "")
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000528 << ", " << utostr(PT->getNumElements()) << ");";
529 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000530 break;
531 }
532 case Type::OpaqueTyID: {
533 const OpaqueType* OT = cast<OpaqueType>(Ty);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000534 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
535 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000536 break;
537 }
538 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000539 error("Invalid TypeID");
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000540 }
541
Reid Spencer74e032a2006-05-29 02:58:15 +0000542 // If the type had a name, make sure we recreate it.
543 const std::string* progTypeName =
544 findTypeName(TheModule->getSymbolTable(),Ty);
545 if (progTypeName)
546 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000547 << typeName << ");";
548 nl(Out);
Reid Spencer74e032a2006-05-29 02:58:15 +0000549
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000550 // Pop us off the type stack
551 TypeStack.pop_back();
Reid Spencer15f7e012006-05-30 21:18:23 +0000552
553 // Indicate that this type is now defined.
554 DefinedTypes.insert(Ty);
555
556 // Early resolve as many unresolved types as possible. Search the unresolved
557 // types map for the type we just printed. Now that its definition is complete
558 // we can resolve any previous references to it. This prevents a cascade of
559 // unresolved types.
560 TypeMap::iterator I = UnresolvedTypes.find(Ty);
561 if (I != UnresolvedTypes.end()) {
562 Out << "cast<OpaqueType>(" << I->second
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000563 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
564 nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +0000565 Out << I->second << " = cast<";
566 switch (Ty->getTypeID()) {
567 case Type::FunctionTyID: Out << "FunctionType"; break;
568 case Type::ArrayTyID: Out << "ArrayType"; break;
569 case Type::StructTyID: Out << "StructType"; break;
570 case Type::PackedTyID: Out << "PackedType"; break;
571 case Type::PointerTyID: Out << "PointerType"; break;
572 case Type::OpaqueTyID: Out << "OpaqueType"; break;
573 default: Out << "NoSuchDerivedType"; break;
574 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000575 Out << ">(" << I->second << "_fwd.get());";
576 nl(Out); nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +0000577 UnresolvedTypes.erase(I);
578 }
579
580 // Finally, separate the type definition from other with a newline.
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000581 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000582
583 // We weren't a recursive type
584 return false;
585}
586
Reid Spencer12803f52006-05-31 17:31:38 +0000587// Prints a type definition. Returns true if it could not resolve all the types
588// in the definition but had to use a forward reference.
589void
590CppWriter::printType(const Type* Ty) {
591 assert(TypeStack.empty());
592 TypeStack.clear();
593 printTypeInternal(Ty);
594 assert(TypeStack.empty());
595}
596
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000597void
598CppWriter::printTypes(const Module* M) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000599
600 // Walk the symbol table and print out all its types
601 const SymbolTable& symtab = M->getSymbolTable();
602 for (SymbolTable::type_const_iterator TI = symtab.type_begin(),
603 TE = symtab.type_end(); TI != TE; ++TI) {
604
605 // For primitive types and types already defined, just add a name
606 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
607 if (TI->second->isPrimitiveType() || TNI != TypeNames.end()) {
608 Out << "mod->addTypeName(\"";
609 printEscapedString(TI->first);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000610 Out << "\", " << getCppName(TI->second) << ");";
611 nl(Out);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000612 // For everything else, define the type
613 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000614 printType(TI->second);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000615 }
616 }
617
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000618 // Add all of the global variables to the value table...
619 for (Module::const_global_iterator I = TheModule->global_begin(),
620 E = TheModule->global_end(); I != E; ++I) {
621 if (I->hasInitializer())
Reid Spencer12803f52006-05-31 17:31:38 +0000622 printType(I->getInitializer()->getType());
623 printType(I->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000624 }
625
626 // Add all the functions to the table
627 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
628 FI != FE; ++FI) {
Reid Spencer12803f52006-05-31 17:31:38 +0000629 printType(FI->getReturnType());
630 printType(FI->getFunctionType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000631 // Add all the function arguments
632 for(Function::const_arg_iterator AI = FI->arg_begin(),
633 AE = FI->arg_end(); AI != AE; ++AI) {
Reid Spencer12803f52006-05-31 17:31:38 +0000634 printType(AI->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000635 }
636
637 // Add all of the basic blocks and instructions
638 for (Function::const_iterator BB = FI->begin(),
639 E = FI->end(); BB != E; ++BB) {
Reid Spencer12803f52006-05-31 17:31:38 +0000640 printType(BB->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000641 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
642 ++I) {
Reid Spencer12803f52006-05-31 17:31:38 +0000643 printType(I->getType());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000644 for (unsigned i = 0; i < I->getNumOperands(); ++i)
Reid Spencer12803f52006-05-31 17:31:38 +0000645 printType(I->getOperand(i)->getType());
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000646 }
647 }
648 }
649}
650
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000651
Reid Spencere0d133f2006-05-29 18:08:06 +0000652// printConstant - Print out a constant pool entry...
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000653void CppWriter::printConstant(const Constant *CV) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000654 // First, if the constant is actually a GlobalValue (variable or function) or
655 // its already in the constant list then we've printed it already and we can
656 // just return.
657 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
Reid Spencere0d133f2006-05-29 18:08:06 +0000658 return;
659
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000660 std::string constName(getCppName(CV));
661 std::string typeName(getCppName(CV->getType()));
662 if (CV->isNullValue()) {
663 Out << "Constant* " << constName << " = Constant::getNullValue("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000664 << typeName << ");";
665 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000666 return;
667 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000668 if (isa<GlobalValue>(CV)) {
669 // Skip variables and functions, we emit them elsewhere
670 return;
671 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000672 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000673 Out << "ConstantBool* " << constName << " = ConstantBool::get("
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000674 << (CB == ConstantBool::True ? "true" : "false")
675 << ");";
676 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000677 Out << "ConstantSInt* " << constName << " = ConstantSInt::get("
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000678 << typeName << ", " << CI->getValue() << ");";
679 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000680 Out << "ConstantUInt* " << constName << " = ConstantUInt::get("
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000681 << typeName << ", " << CI->getValue() << ");";
682 } else if (isa<ConstantAggregateZero>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000683 Out << "ConstantAggregateZero* " << constName
684 << " = ConstantAggregateZero::get(" << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000685 } else if (isa<ConstantPointerNull>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000686 Out << "ConstantPointerNull* " << constName
687 << " = ConstanPointerNull::get(" << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000688 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
Reid Spencerf977e7b2006-06-01 23:43:47 +0000689 Out << "ConstantFP* " << constName << " = ";
Reid Spencer12803f52006-05-31 17:31:38 +0000690 printCFP(CFP);
Reid Spencerf977e7b2006-06-01 23:43:47 +0000691 Out << ";";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000692 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000693 if (CA->isString() && CA->getType()->getElementType() == Type::SByteTy) {
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000694 Out << "Constant* " << constName << " = ConstantArray::get(\"";
Reid Spencere0d133f2006-05-29 18:08:06 +0000695 printEscapedString(CA->getAsString());
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000696 // Determine if we want null termination or not.
697 if (CA->getType()->getNumElements() <= CA->getAsString().length())
Reid Spencer15f7e012006-05-30 21:18:23 +0000698 Out << "\", false";// No null terminator
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000699 else
Reid Spencer15f7e012006-05-30 21:18:23 +0000700 Out << "\", true"; // Indicate that the null terminator should be added.
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000701 Out << ");";
702 } else {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000703 Out << "std::vector<Constant*> " << constName << "_elems;";
704 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000705 unsigned N = CA->getNumOperands();
706 for (unsigned i = 0; i < N; ++i) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000707 printConstant(CA->getOperand(i)); // recurse to print operands
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000708 Out << constName << "_elems.push_back("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000709 << getCppName(CA->getOperand(i)) << ");";
710 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000711 }
712 Out << "Constant* " << constName << " = ConstantArray::get("
713 << typeName << ", " << constName << "_elems);";
714 }
715 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000716 Out << "std::vector<Constant*> " << constName << "_fields;";
717 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000718 unsigned N = CS->getNumOperands();
719 for (unsigned i = 0; i < N; i++) {
720 printConstant(CS->getOperand(i));
721 Out << constName << "_fields.push_back("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000722 << getCppName(CS->getOperand(i)) << ");";
723 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000724 }
725 Out << "Constant* " << constName << " = ConstantStruct::get("
726 << typeName << ", " << constName << "_fields);";
727 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000728 Out << "std::vector<Constant*> " << constName << "_elems;";
729 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000730 unsigned N = CP->getNumOperands();
731 for (unsigned i = 0; i < N; ++i) {
732 printConstant(CP->getOperand(i));
733 Out << constName << "_elems.push_back("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000734 << getCppName(CP->getOperand(i)) << ");";
735 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000736 }
737 Out << "Constant* " << constName << " = ConstantPacked::get("
738 << typeName << ", " << constName << "_elems);";
739 } else if (isa<UndefValue>(CV)) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000740 Out << "UndefValue* " << constName << " = UndefValue::get("
Reid Spencere0d133f2006-05-29 18:08:06 +0000741 << typeName << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000742 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000743 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000744 Out << "std::vector<Constant*> " << constName << "_indices;";
745 nl(Out);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000746 printConstant(CE->getOperand(0));
Reid Spencere0d133f2006-05-29 18:08:06 +0000747 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000748 printConstant(CE->getOperand(i));
Reid Spencere0d133f2006-05-29 18:08:06 +0000749 Out << constName << "_indices.push_back("
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000750 << getCppName(CE->getOperand(i)) << ");";
751 nl(Out);
Reid Spencere0d133f2006-05-29 18:08:06 +0000752 }
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000753 Out << "Constant* " << constName
754 << " = ConstantExpr::getGetElementPtr("
755 << getCppName(CE->getOperand(0)) << ", "
756 << constName << "_indices);";
Reid Spencere0d133f2006-05-29 18:08:06 +0000757 } else if (CE->getOpcode() == Instruction::Cast) {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000758 printConstant(CE->getOperand(0));
Reid Spencere0d133f2006-05-29 18:08:06 +0000759 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
760 Out << getCppName(CE->getOperand(0)) << ", " << getCppName(CE->getType())
761 << ");";
762 } else {
Reid Spencer1a2a0cc2006-05-30 10:21:41 +0000763 unsigned N = CE->getNumOperands();
764 for (unsigned i = 0; i < N; ++i ) {
765 printConstant(CE->getOperand(i));
766 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000767 Out << "Constant* " << constName << " = ConstantExpr::";
768 switch (CE->getOpcode()) {
769 case Instruction::Add: Out << "getAdd"; break;
770 case Instruction::Sub: Out << "getSub"; break;
771 case Instruction::Mul: Out << "getMul"; break;
772 case Instruction::Div: Out << "getDiv"; break;
773 case Instruction::Rem: Out << "getRem"; break;
774 case Instruction::And: Out << "getAnd"; break;
775 case Instruction::Or: Out << "getOr"; break;
776 case Instruction::Xor: Out << "getXor"; break;
777 case Instruction::SetEQ: Out << "getSetEQ"; break;
778 case Instruction::SetNE: Out << "getSetNE"; break;
779 case Instruction::SetLE: Out << "getSetLE"; break;
780 case Instruction::SetGE: Out << "getSetGE"; break;
781 case Instruction::SetLT: Out << "getSetLT"; break;
782 case Instruction::SetGT: Out << "getSetGT"; break;
783 case Instruction::Shl: Out << "getShl"; break;
784 case Instruction::Shr: Out << "getShr"; break;
785 case Instruction::Select: Out << "getSelect"; break;
786 case Instruction::ExtractElement: Out << "getExtractElement"; break;
787 case Instruction::InsertElement: Out << "getInsertElement"; break;
788 case Instruction::ShuffleVector: Out << "getShuffleVector"; break;
789 default:
Reid Spencer12803f52006-05-31 17:31:38 +0000790 error("Invalid constant expression");
Reid Spencere0d133f2006-05-29 18:08:06 +0000791 break;
792 }
793 Out << getCppName(CE->getOperand(0));
794 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
795 Out << ", " << getCppName(CE->getOperand(i));
796 Out << ");";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000797 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000798 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000799 error("Bad Constant");
Reid Spencere0d133f2006-05-29 18:08:06 +0000800 Out << "Constant* " << constName << " = 0; ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000801 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000802 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000803}
804
Reid Spencer12803f52006-05-31 17:31:38 +0000805void
806CppWriter::printConstants(const Module* M) {
807 // Traverse all the global variables looking for constant initializers
808 for (Module::const_global_iterator I = TheModule->global_begin(),
809 E = TheModule->global_end(); I != E; ++I)
810 if (I->hasInitializer())
811 printConstant(I->getInitializer());
812
813 // Traverse the LLVM functions looking for constants
814 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
815 FI != FE; ++FI) {
816 // Add all of the basic blocks and instructions
817 for (Function::const_iterator BB = FI->begin(),
818 E = FI->end(); BB != E; ++BB) {
819 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
820 ++I) {
821 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
822 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
823 printConstant(C);
824 }
825 }
826 }
827 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000828 }
Reid Spencer66c87342006-05-30 03:43:49 +0000829}
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000830
Reid Spencer12803f52006-05-31 17:31:38 +0000831void CppWriter::printVariableUses(const GlobalVariable *GV) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000832 nl(Out) << "// Type Definitions";
833 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000834 printType(GV->getType());
835 if (GV->hasInitializer()) {
836 Constant* Init = GV->getInitializer();
837 printType(Init->getType());
838 if (Function* F = dyn_cast<Function>(Init)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000839 nl(Out)<< "/ Function Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000840 printFunctionHead(F);
841 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000842 nl(Out) << "// Global Variable Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000843 printVariableHead(gv);
844 } else {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000845 nl(Out) << "// Constant Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000846 printConstant(gv);
847 }
848 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000849 nl(Out) << "// Global Variable Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000850 printVariableBody(gv);
Reid Spencere0d133f2006-05-29 18:08:06 +0000851 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000852 }
Reid Spencer12803f52006-05-31 17:31:38 +0000853}
Reid Spencer15f7e012006-05-30 21:18:23 +0000854
Reid Spencer12803f52006-05-31 17:31:38 +0000855void CppWriter::printVariableHead(const GlobalVariable *GV) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000856 nl(Out) << "GlobalVariable* " << getCppName(GV);
Reid Spencerf977e7b2006-06-01 23:43:47 +0000857 if (is_inline) {
858 Out << " = mod->getGlobalVariable(";
859 printEscapedString(GV->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000860 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
861 nl(Out) << "if (!" << getCppName(GV) << ") {";
862 in(); nl(Out) << getCppName(GV);
Reid Spencerf977e7b2006-06-01 23:43:47 +0000863 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000864 Out << " = new GlobalVariable(";
865 nl(Out) << "/*Type=*/";
Reid Spencer12803f52006-05-31 17:31:38 +0000866 printCppName(GV->getType()->getElementType());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000867 Out << ",";
868 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
869 Out << ",";
870 nl(Out) << "/*Linkage=*/";
Reid Spencer12803f52006-05-31 17:31:38 +0000871 printLinkageType(GV->getLinkage());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000872 Out << ",";
873 nl(Out) << "/*Initializer=*/0, ";
Reid Spencer12803f52006-05-31 17:31:38 +0000874 if (GV->hasInitializer()) {
875 Out << "// has initializer, specified below";
Reid Spencer15f7e012006-05-30 21:18:23 +0000876 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000877 nl(Out) << "/*Name=*/\"";
Reid Spencer12803f52006-05-31 17:31:38 +0000878 printEscapedString(GV->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000879 Out << "\",";
880 nl(Out) << "mod);";
881 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000882
883 if (GV->hasSection()) {
884 printCppName(GV);
885 Out << "->setSection(\"";
886 printEscapedString(GV->getSection());
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000887 Out << "\");";
888 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000889 }
890 if (GV->getAlignment()) {
891 printCppName(GV);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000892 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
893 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000894 };
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000895 if (is_inline) {
896 out(); Out << "}"; nl(Out);
897 }
Reid Spencer12803f52006-05-31 17:31:38 +0000898}
899
900void
901CppWriter::printVariableBody(const GlobalVariable *GV) {
902 if (GV->hasInitializer()) {
903 printCppName(GV);
904 Out << "->setInitializer(";
905 //if (!isa<GlobalValue(GV->getInitializer()))
906 //else
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000907 Out << getCppName(GV->getInitializer()) << ");";
908 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000909 }
910}
911
912std::string
913CppWriter::getOpName(Value* V) {
914 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
915 return getCppName(V);
916
917 // See if its alread in the map of forward references, if so just return the
918 // name we already set up for it
919 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
920 if (I != ForwardRefs.end())
921 return I->second;
922
923 // This is a new forward reference. Generate a unique name for it
924 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
925
926 // Yes, this is a hack. An Argument is the smallest instantiable value that
927 // we can make as a placeholder for the real value. We'll replace these
928 // Argument instances later.
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000929 Out << "Argument* " << result << " = new Argument("
930 << getCppName(V->getType()) << ");";
931 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +0000932 ForwardRefs[V] = result;
933 return result;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000934}
935
Reid Spencere0d133f2006-05-29 18:08:06 +0000936// printInstruction - This member is called for each Instruction in a function.
937void
Reid Spencer12803f52006-05-31 17:31:38 +0000938CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
Reid Spencere0d133f2006-05-29 18:08:06 +0000939 std::string iName(getCppName(I));
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000940
Reid Spencer15f7e012006-05-30 21:18:23 +0000941 // Before we emit this instruction, we need to take care of generating any
942 // forward references. So, we get the names of all the operands in advance
943 std::string* opNames = new std::string[I->getNumOperands()];
944 for (unsigned i = 0; i < I->getNumOperands(); i++) {
945 opNames[i] = getOpName(I->getOperand(i));
946 }
947
Reid Spencere0d133f2006-05-29 18:08:06 +0000948 switch (I->getOpcode()) {
949 case Instruction::Ret: {
950 const ReturnInst* ret = cast<ReturnInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000951 Out << "ReturnInst* " << iName << " = new ReturnInst("
Reid Spencer15f7e012006-05-30 21:18:23 +0000952 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
Reid Spencere0d133f2006-05-29 18:08:06 +0000953 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000954 }
Reid Spencere0d133f2006-05-29 18:08:06 +0000955 case Instruction::Br: {
956 const BranchInst* br = cast<BranchInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000957 Out << "BranchInst* " << iName << " = new BranchInst(" ;
Reid Spencere0d133f2006-05-29 18:08:06 +0000958 if (br->getNumOperands() == 3 ) {
Reid Spencer15f7e012006-05-30 21:18:23 +0000959 Out << opNames[0] << ", "
960 << opNames[1] << ", "
961 << opNames[2] << ", ";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +0000962
Reid Spencere0d133f2006-05-29 18:08:06 +0000963 } else if (br->getNumOperands() == 1) {
Reid Spencer15f7e012006-05-30 21:18:23 +0000964 Out << opNames[0] << ", ";
Reid Spencere0d133f2006-05-29 18:08:06 +0000965 } else {
Reid Spencer12803f52006-05-31 17:31:38 +0000966 error("Branch with 2 operands?");
Reid Spencere0d133f2006-05-29 18:08:06 +0000967 }
968 Out << bbname << ");";
969 break;
970 }
Reid Spencer66c87342006-05-30 03:43:49 +0000971 case Instruction::Switch: {
972 const SwitchInst* sw = cast<SwitchInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000973 Out << "SwitchInst* " << iName << " = new SwitchInst("
Reid Spencer15f7e012006-05-30 21:18:23 +0000974 << opNames[0] << ", "
975 << opNames[1] << ", "
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000976 << sw->getNumCases() << ", " << bbname << ");";
977 nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +0000978 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000979 Out << iName << "->addCase("
Reid Spencer15f7e012006-05-30 21:18:23 +0000980 << opNames[i] << ", "
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000981 << opNames[i+1] << ");";
982 nl(Out);
Reid Spencer66c87342006-05-30 03:43:49 +0000983 }
984 break;
985 }
986 case Instruction::Invoke: {
987 const InvokeInst* inv = cast<InvokeInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +0000988 Out << "std::vector<Value*> " << iName << "_params;";
989 nl(Out);
990 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
991 Out << iName << "_params.push_back("
992 << opNames[i] << ");";
993 nl(Out);
994 }
995 Out << "InvokeInst* " << iName << " = new InvokeInst("
Reid Spencer15f7e012006-05-30 21:18:23 +0000996 << opNames[0] << ", "
997 << opNames[1] << ", "
998 << opNames[2] << ", "
Reid Spencer66c87342006-05-30 03:43:49 +0000999 << iName << "_params, \"";
1000 printEscapedString(inv->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001001 Out << "\", " << bbname << ");";
1002 nl(Out) << iName << "->setCallingConv(";
Reid Spencer66c87342006-05-30 03:43:49 +00001003 printCallingConv(inv->getCallingConv());
1004 Out << ");";
1005 break;
1006 }
1007 case Instruction::Unwind: {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001008 Out << "UnwindInst* " << iName << " = new UnwindInst("
Reid Spencer66c87342006-05-30 03:43:49 +00001009 << bbname << ");";
1010 break;
1011 }
1012 case Instruction::Unreachable:{
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001013 Out << "UnreachableInst* " << iName << " = new UnreachableInst("
Reid Spencer66c87342006-05-30 03:43:49 +00001014 << bbname << ");";
1015 break;
1016 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001017 case Instruction::Add:
1018 case Instruction::Sub:
1019 case Instruction::Mul:
1020 case Instruction::Div:
1021 case Instruction::Rem:
1022 case Instruction::And:
1023 case Instruction::Or:
1024 case Instruction::Xor:
Reid Spencer66c87342006-05-30 03:43:49 +00001025 case Instruction::Shl:
1026 case Instruction::Shr:{
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001027 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
Reid Spencer66c87342006-05-30 03:43:49 +00001028 switch (I->getOpcode()) {
1029 case Instruction::Add: Out << "Instruction::Add"; break;
1030 case Instruction::Sub: Out << "Instruction::Sub"; break;
1031 case Instruction::Mul: Out << "Instruction::Mul"; break;
1032 case Instruction::Div: Out << "Instruction::Div"; break;
1033 case Instruction::Rem: Out << "Instruction::Rem"; break;
1034 case Instruction::And: Out << "Instruction::And"; break;
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001035 case Instruction::Or: Out << "Instruction::Or"; break;
Reid Spencer66c87342006-05-30 03:43:49 +00001036 case Instruction::Xor: Out << "Instruction::Xor"; break;
1037 case Instruction::Shl: Out << "Instruction::Shl"; break;
1038 case Instruction::Shr: Out << "Instruction::Shr"; break;
1039 default: Out << "Instruction::BadOpCode"; break;
1040 }
Reid Spencer15f7e012006-05-30 21:18:23 +00001041 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001042 printEscapedString(I->getName());
1043 Out << "\", " << bbname << ");";
1044 break;
1045 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001046 case Instruction::SetEQ:
1047 case Instruction::SetNE:
1048 case Instruction::SetLE:
1049 case Instruction::SetGE:
1050 case Instruction::SetLT:
Reid Spencer66c87342006-05-30 03:43:49 +00001051 case Instruction::SetGT: {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001052 Out << "SetCondInst* " << iName << " = new SetCondInst(";
Reid Spencer66c87342006-05-30 03:43:49 +00001053 switch (I->getOpcode()) {
1054 case Instruction::SetEQ: Out << "Instruction::SetEQ"; break;
1055 case Instruction::SetNE: Out << "Instruction::SetNE"; break;
1056 case Instruction::SetLE: Out << "Instruction::SetLE"; break;
1057 case Instruction::SetGE: Out << "Instruction::SetGE"; break;
1058 case Instruction::SetLT: Out << "Instruction::SetLT"; break;
1059 case Instruction::SetGT: Out << "Instruction::SetGT"; break;
1060 default: Out << "Instruction::BadOpCode"; break;
1061 }
Reid Spencer15f7e012006-05-30 21:18:23 +00001062 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001063 printEscapedString(I->getName());
1064 Out << "\", " << bbname << ");";
1065 break;
1066 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001067 case Instruction::Malloc: {
1068 const MallocInst* mallocI = cast<MallocInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001069 Out << "MallocInst* " << iName << " = new MallocInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001070 << getCppName(mallocI->getAllocatedType()) << ", ";
1071 if (mallocI->isArrayAllocation())
Reid Spencer15f7e012006-05-30 21:18:23 +00001072 Out << opNames[0] << ", " ;
Reid Spencere0d133f2006-05-29 18:08:06 +00001073 Out << "\"";
1074 printEscapedString(mallocI->getName());
1075 Out << "\", " << bbname << ");";
1076 if (mallocI->getAlignment())
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001077 nl(Out) << iName << "->setAlignment("
Reid Spencere0d133f2006-05-29 18:08:06 +00001078 << mallocI->getAlignment() << ");";
1079 break;
1080 }
Reid Spencer66c87342006-05-30 03:43:49 +00001081 case Instruction::Free: {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001082 Out << "FreeInst* " << iName << " = new FreeInst("
Reid Spencer66c87342006-05-30 03:43:49 +00001083 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1084 break;
1085 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001086 case Instruction::Alloca: {
1087 const AllocaInst* allocaI = cast<AllocaInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001088 Out << "AllocaInst* " << iName << " = new AllocaInst("
Reid Spencere0d133f2006-05-29 18:08:06 +00001089 << getCppName(allocaI->getAllocatedType()) << ", ";
1090 if (allocaI->isArrayAllocation())
Reid Spencer15f7e012006-05-30 21:18:23 +00001091 Out << opNames[0] << ", ";
Reid Spencere0d133f2006-05-29 18:08:06 +00001092 Out << "\"";
1093 printEscapedString(allocaI->getName());
1094 Out << "\", " << bbname << ");";
1095 if (allocaI->getAlignment())
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001096 nl(Out) << iName << "->setAlignment("
Reid Spencere0d133f2006-05-29 18:08:06 +00001097 << allocaI->getAlignment() << ");";
1098 break;
1099 }
Reid Spencer66c87342006-05-30 03:43:49 +00001100 case Instruction::Load:{
1101 const LoadInst* load = cast<LoadInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001102 Out << "LoadInst* " << iName << " = new LoadInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001103 << opNames[0] << ", \"";
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001104 printEscapedString(load->getName());
1105 Out << "\", " << (load->isVolatile() ? "true" : "false" )
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001106 << ", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001107 break;
1108 }
Reid Spencere0d133f2006-05-29 18:08:06 +00001109 case Instruction::Store: {
1110 const StoreInst* store = cast<StoreInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001111 Out << "StoreInst* " << iName << " = new StoreInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001112 << opNames[0] << ", "
1113 << opNames[1] << ", "
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001114 << (store->isVolatile() ? "true" : "false")
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001115 << ", " << bbname << ");";
Reid Spencere0d133f2006-05-29 18:08:06 +00001116 break;
1117 }
1118 case Instruction::GetElementPtr: {
1119 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1120 if (gep->getNumOperands() <= 2) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001121 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001122 << opNames[0];
Reid Spencere0d133f2006-05-29 18:08:06 +00001123 if (gep->getNumOperands() == 2)
Reid Spencer15f7e012006-05-30 21:18:23 +00001124 Out << ", " << opNames[1];
Reid Spencere0d133f2006-05-29 18:08:06 +00001125 } else {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001126 Out << "std::vector<Value*> " << iName << "_indices;";
1127 nl(Out);
Reid Spencere0d133f2006-05-29 18:08:06 +00001128 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001129 Out << iName << "_indices.push_back("
1130 << opNames[i] << ");";
1131 nl(Out);
Reid Spencere0d133f2006-05-29 18:08:06 +00001132 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001133 Out << "Instruction* " << iName << " = new GetElementPtrInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001134 << opNames[0] << ", " << iName << "_indices";
Reid Spencere0d133f2006-05-29 18:08:06 +00001135 }
1136 Out << ", \"";
1137 printEscapedString(gep->getName());
1138 Out << "\", " << bbname << ");";
1139 break;
1140 }
Reid Spencer66c87342006-05-30 03:43:49 +00001141 case Instruction::PHI: {
1142 const PHINode* phi = cast<PHINode>(I);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001143
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001144 Out << "PHINode* " << iName << " = new PHINode("
Reid Spencer66c87342006-05-30 03:43:49 +00001145 << getCppName(phi->getType()) << ", \"";
1146 printEscapedString(phi->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001147 Out << "\", " << bbname << ");";
1148 nl(Out) << iName << "->reserveOperandSpace("
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001149 << phi->getNumIncomingValues()
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001150 << ");";
1151 nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +00001152 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001153 Out << iName << "->addIncoming("
1154 << opNames[i] << ", " << opNames[i+1] << ");";
1155 nl(Out);
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001156 }
Reid Spencer66c87342006-05-30 03:43:49 +00001157 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001158 }
Reid Spencer66c87342006-05-30 03:43:49 +00001159 case Instruction::Cast: {
1160 const CastInst* cst = cast<CastInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001161 Out << "CastInst* " << iName << " = new CastInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001162 << opNames[0] << ", "
Reid Spencer66c87342006-05-30 03:43:49 +00001163 << getCppName(cst->getType()) << ", \"";
1164 printEscapedString(cst->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001165 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001166 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001167 }
Reid Spencer66c87342006-05-30 03:43:49 +00001168 case Instruction::Call:{
1169 const CallInst* call = cast<CallInst>(I);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001170 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001171 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001172 << getCppName(ila->getFunctionType()) << ", \""
1173 << ila->getAsmString() << "\", \""
1174 << ila->getConstraintString() << "\","
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001175 << (ila->hasSideEffects() ? "true" : "false") << ");";
1176 nl(Out);
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001177 }
Reid Spencer66c87342006-05-30 03:43:49 +00001178 if (call->getNumOperands() > 3) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001179 Out << "std::vector<Value*> " << iName << "_params;";
1180 nl(Out);
1181 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1182 Out << iName << "_params.push_back(" << opNames[i] << ");";
1183 nl(Out);
1184 }
1185 Out << "CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001186 << opNames[0] << ", " << iName << "_params, \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001187 } else if (call->getNumOperands() == 3) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001188 Out << "CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001189 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001190 } else if (call->getNumOperands() == 2) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001191 Out << "CallInst* " << iName << " = new CallInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001192 << opNames[0] << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001193 } else {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001194 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
Reid Spencer15f7e012006-05-30 21:18:23 +00001195 << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001196 }
1197 printEscapedString(call->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001198 Out << "\", " << bbname << ");";
1199 nl(Out) << iName << "->setCallingConv(";
Reid Spencer66c87342006-05-30 03:43:49 +00001200 printCallingConv(call->getCallingConv());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001201 Out << ");";
1202 nl(Out) << iName << "->setTailCall("
Reid Spencer1a2a0cc2006-05-30 10:21:41 +00001203 << (call->isTailCall() ? "true":"false");
Reid Spencer66c87342006-05-30 03:43:49 +00001204 Out << ");";
1205 break;
1206 }
1207 case Instruction::Select: {
1208 const SelectInst* sel = cast<SelectInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001209 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
Reid Spencer15f7e012006-05-30 21:18:23 +00001210 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001211 printEscapedString(sel->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001212 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001213 break;
1214 }
1215 case Instruction::UserOp1:
1216 /// FALL THROUGH
1217 case Instruction::UserOp2: {
1218 /// FIXME: What should be done here?
1219 break;
1220 }
1221 case Instruction::VAArg: {
1222 const VAArgInst* va = cast<VAArgInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001223 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
Reid Spencer15f7e012006-05-30 21:18:23 +00001224 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001225 printEscapedString(va->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001226 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001227 break;
1228 }
1229 case Instruction::ExtractElement: {
1230 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001231 Out << "ExtractElementInst* " << getCppName(eei)
Reid Spencer15f7e012006-05-30 21:18:23 +00001232 << " = new ExtractElementInst(" << opNames[0]
1233 << ", " << opNames[1] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001234 printEscapedString(eei->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001235 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001236 break;
1237 }
1238 case Instruction::InsertElement: {
1239 const InsertElementInst* iei = cast<InsertElementInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001240 Out << "InsertElementInst* " << getCppName(iei)
Reid Spencer15f7e012006-05-30 21:18:23 +00001241 << " = new InsertElementInst(" << opNames[0]
1242 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001243 printEscapedString(iei->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001244 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001245 break;
1246 }
1247 case Instruction::ShuffleVector: {
1248 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001249 Out << "ShuffleVectorInst* " << getCppName(svi)
Reid Spencer15f7e012006-05-30 21:18:23 +00001250 << " = new ShuffleVectorInst(" << opNames[0]
1251 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
Reid Spencer66c87342006-05-30 03:43:49 +00001252 printEscapedString(svi->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001253 Out << "\", " << bbname << ");";
Reid Spencer66c87342006-05-30 03:43:49 +00001254 break;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001255 }
1256 }
Reid Spencer68464b72006-06-15 16:09:59 +00001257 DefinedValues.insert(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001258 nl(Out);
Reid Spencer15f7e012006-05-30 21:18:23 +00001259 delete [] opNames;
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001260}
1261
Reid Spencer12803f52006-05-31 17:31:38 +00001262// Print out the types, constants and declarations needed by one function
1263void CppWriter::printFunctionUses(const Function* F) {
1264
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001265 nl(Out) << "// Type Definitions"; nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001266 if (!is_inline) {
1267 // Print the function's return type
1268 printType(F->getReturnType());
Reid Spencer12803f52006-05-31 17:31:38 +00001269
Reid Spencerf977e7b2006-06-01 23:43:47 +00001270 // Print the function's function type
1271 printType(F->getFunctionType());
Reid Spencer12803f52006-05-31 17:31:38 +00001272
Reid Spencerf977e7b2006-06-01 23:43:47 +00001273 // Print the types of each of the function's arguments
1274 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1275 AI != AE; ++AI) {
1276 printType(AI->getType());
1277 }
Reid Spencer12803f52006-05-31 17:31:38 +00001278 }
1279
1280 // Print type definitions for every type referenced by an instruction and
1281 // make a note of any global values or constants that are referenced
1282 std::vector<GlobalValue*> gvs;
1283 std::vector<Constant*> consts;
1284 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1285 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1286 I != E; ++I) {
1287 // Print the type of the instruction itself
1288 printType(I->getType());
1289
1290 // Print the type of each of the instruction's operands
1291 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1292 Value* operand = I->getOperand(i);
1293 printType(operand->getType());
1294 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1295 gvs.push_back(GV);
1296 else if (Constant* C = dyn_cast<Constant>(operand))
1297 consts.push_back(C);
1298 }
1299 }
1300 }
1301
1302 // Print the function declarations for any functions encountered
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001303 nl(Out) << "// Function Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001304 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1305 I != E; ++I) {
Reid Spencerf977e7b2006-06-01 23:43:47 +00001306 if (Function* Fun = dyn_cast<Function>(*I)) {
1307 if (!is_inline || Fun != F)
1308 printFunctionHead(Fun);
1309 }
Reid Spencer12803f52006-05-31 17:31:38 +00001310 }
1311
1312 // Print the global variable declarations for any variables encountered
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001313 nl(Out) << "// Global Variable Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001314 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1315 I != E; ++I) {
1316 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1317 printVariableHead(F);
1318 }
1319
1320 // Print the constants found
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001321 nl(Out) << "// Constant Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001322 for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1323 I != E; ++I) {
Reid Spencerf977e7b2006-06-01 23:43:47 +00001324 printConstant(*I);
Reid Spencer12803f52006-05-31 17:31:38 +00001325 }
1326
1327 // Process the global variables definitions now that all the constants have
1328 // been emitted. These definitions just couple the gvars with their constant
1329 // initializers.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001330 nl(Out) << "// Global Variable Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001331 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1332 I != E; ++I) {
1333 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1334 printVariableBody(GV);
1335 }
1336}
1337
1338void CppWriter::printFunctionHead(const Function* F) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001339 nl(Out) << "Function* " << getCppName(F);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001340 if (is_inline) {
1341 Out << " = mod->getFunction(\"";
1342 printEscapedString(F->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001343 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1344 nl(Out) << "if (!" << getCppName(F) << ") {";
1345 nl(Out) << getCppName(F);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001346 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001347 Out<< " = new Function(";
1348 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1349 nl(Out) << "/*Linkage=*/";
Reid Spencer12803f52006-05-31 17:31:38 +00001350 printLinkageType(F->getLinkage());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001351 Out << ",";
1352 nl(Out) << "/*Name=*/\"";
Reid Spencer12803f52006-05-31 17:31:38 +00001353 printEscapedString(F->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001354 Out << "\", mod); " << (F->isExternal()? "// (external, no body)" : "");
1355 nl(Out,-1);
Reid Spencer12803f52006-05-31 17:31:38 +00001356 printCppName(F);
1357 Out << "->setCallingConv(";
1358 printCallingConv(F->getCallingConv());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001359 Out << ");";
1360 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001361 if (F->hasSection()) {
1362 printCppName(F);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001363 Out << "->setSection(\"" << F->getSection() << "\");";
1364 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001365 }
1366 if (F->getAlignment()) {
1367 printCppName(F);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001368 Out << "->setAlignment(" << F->getAlignment() << ");";
1369 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001370 }
Reid Spencerf977e7b2006-06-01 23:43:47 +00001371 if (is_inline) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001372 Out << "}";
1373 nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001374 }
Reid Spencer12803f52006-05-31 17:31:38 +00001375}
1376
1377void CppWriter::printFunctionBody(const Function *F) {
1378 if (F->isExternal())
1379 return; // external functions have no bodies.
1380
1381 // Clear the DefinedValues and ForwardRefs maps because we can't have
1382 // cross-function forward refs
1383 ForwardRefs.clear();
1384 DefinedValues.clear();
1385
1386 // Create all the argument values
Reid Spencerf977e7b2006-06-01 23:43:47 +00001387 if (!is_inline) {
1388 if (!F->arg_empty()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001389 Out << "Function::arg_iterator args = " << getCppName(F)
1390 << "->arg_begin();";
1391 nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001392 }
1393 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1394 AI != AE; ++AI) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001395 Out << "Value* " << getCppName(AI) << " = args++;";
1396 nl(Out);
1397 if (AI->hasName()) {
1398 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1399 nl(Out);
1400 }
Reid Spencerf977e7b2006-06-01 23:43:47 +00001401 }
Reid Spencer12803f52006-05-31 17:31:38 +00001402 }
1403
1404 // Create all the basic blocks
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001405 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001406 for (Function::const_iterator BI = F->begin(), BE = F->end();
1407 BI != BE; ++BI) {
1408 std::string bbname(getCppName(BI));
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001409 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
Reid Spencer12803f52006-05-31 17:31:38 +00001410 if (BI->hasName())
1411 printEscapedString(BI->getName());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001412 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1413 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001414 }
1415
1416 // Output all of its basic blocks... for the function
1417 for (Function::const_iterator BI = F->begin(), BE = F->end();
1418 BI != BE; ++BI) {
1419 std::string bbname(getCppName(BI));
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001420 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1421 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001422
1423 // Output all of the instructions in the basic block...
1424 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1425 I != E; ++I) {
1426 printInstruction(I,bbname);
1427 }
1428 }
1429
1430 // Loop over the ForwardRefs and resolve them now that all instructions
1431 // are generated.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001432 if (!ForwardRefs.empty()) {
1433 nl(Out) << "// Resolve Forward References";
1434 nl(Out);
1435 }
1436
Reid Spencer12803f52006-05-31 17:31:38 +00001437 while (!ForwardRefs.empty()) {
1438 ForwardRefMap::iterator I = ForwardRefs.begin();
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001439 Out << I->second << "->replaceAllUsesWith("
1440 << getCppName(I->first) << "); delete " << I->second << ";";
1441 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001442 ForwardRefs.erase(I);
1443 }
1444}
1445
Reid Spencerf977e7b2006-06-01 23:43:47 +00001446void CppWriter::printInline(const std::string& fname, const std::string& func) {
1447 const Function* F = TheModule->getNamedFunction(func);
1448 if (!F) {
1449 error(std::string("Function '") + func + "' not found in input module");
1450 return;
1451 }
1452 if (F->isExternal()) {
1453 error(std::string("Function '") + func + "' is external!");
1454 return;
1455 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001456 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
Reid Spencerf977e7b2006-06-01 23:43:47 +00001457 << getCppName(F);
1458 unsigned arg_count = 1;
1459 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1460 AI != AE; ++AI) {
1461 Out << ", Value* arg_" << arg_count;
1462 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001463 Out << ") {";
1464 nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001465 is_inline = true;
1466 printFunctionUses(F);
1467 printFunctionBody(F);
1468 is_inline = false;
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001469 Out << "return " << getCppName(F->begin()) << ";";
1470 nl(Out) << "}";
1471 nl(Out);
Reid Spencerf977e7b2006-06-01 23:43:47 +00001472}
1473
Reid Spencer12803f52006-05-31 17:31:38 +00001474void CppWriter::printModuleBody() {
1475 // Print out all the type definitions
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001476 nl(Out) << "// Type Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001477 printTypes(TheModule);
1478
1479 // Functions can call each other and global variables can reference them so
1480 // define all the functions first before emitting their function bodies.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001481 nl(Out) << "// Function Declarations"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001482 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1483 I != E; ++I)
1484 printFunctionHead(I);
1485
1486 // Process the global variables declarations. We can't initialze them until
1487 // after the constants are printed so just print a header for each global
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001488 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001489 for (Module::const_global_iterator I = TheModule->global_begin(),
1490 E = TheModule->global_end(); I != E; ++I) {
1491 printVariableHead(I);
1492 }
1493
1494 // Print out all the constants definitions. Constants don't recurse except
1495 // through GlobalValues. All GlobalValues have been declared at this point
1496 // so we can proceed to generate the constants.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001497 nl(Out) << "// Constant Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001498 printConstants(TheModule);
1499
1500 // Process the global variables definitions now that all the constants have
1501 // been emitted. These definitions just couple the gvars with their constant
1502 // initializers.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001503 nl(Out) << "// Global Variable Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001504 for (Module::const_global_iterator I = TheModule->global_begin(),
1505 E = TheModule->global_end(); I != E; ++I) {
1506 printVariableBody(I);
1507 }
1508
1509 // Finally, we can safely put out all of the function bodies.
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001510 nl(Out) << "// Function Definitions"; nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001511 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1512 I != E; ++I) {
1513 if (!I->isExternal()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001514 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1515 << ")";
1516 nl(Out) << "{";
1517 nl(Out,1);
Reid Spencer12803f52006-05-31 17:31:38 +00001518 printFunctionBody(I);
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001519 nl(Out,-1) << "}";
1520 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001521 }
1522 }
1523}
1524
1525void CppWriter::printProgram(
1526 const std::string& fname,
1527 const std::string& mName
1528) {
1529 Out << "#include <llvm/Module.h>\n";
1530 Out << "#include <llvm/DerivedTypes.h>\n";
1531 Out << "#include <llvm/Constants.h>\n";
1532 Out << "#include <llvm/GlobalVariable.h>\n";
1533 Out << "#include <llvm/Function.h>\n";
1534 Out << "#include <llvm/CallingConv.h>\n";
1535 Out << "#include <llvm/BasicBlock.h>\n";
1536 Out << "#include <llvm/Instructions.h>\n";
1537 Out << "#include <llvm/InlineAsm.h>\n";
Reid Spencerf977e7b2006-06-01 23:43:47 +00001538 Out << "#include <llvm/Support/MathExtras.h>\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001539 Out << "#include <llvm/Pass.h>\n";
1540 Out << "#include <llvm/PassManager.h>\n";
1541 Out << "#include <llvm/Analysis/Verifier.h>\n";
1542 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1543 Out << "#include <algorithm>\n";
1544 Out << "#include <iostream>\n\n";
1545 Out << "using namespace llvm;\n\n";
1546 Out << "Module* " << fname << "();\n\n";
1547 Out << "int main(int argc, char**argv) {\n";
1548 Out << " Module* Mod = makeLLVMModule();\n";
1549 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1550 Out << " std::cerr.flush();\n";
1551 Out << " std::cout.flush();\n";
1552 Out << " PassManager PM;\n";
1553 Out << " PM.add(new PrintModulePass(&std::cout));\n";
1554 Out << " PM.run(*Mod);\n";
1555 Out << " return 0;\n";
1556 Out << "}\n\n";
1557 printModule(fname,mName);
1558}
1559
1560void CppWriter::printModule(
1561 const std::string& fname,
1562 const std::string& mName
1563) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001564 nl(Out) << "Module* " << fname << "() {";
1565 nl(Out,1) << "// Module Construction";
1566 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1567 nl(Out) << "mod->setEndianness(";
Reid Spencer12803f52006-05-31 17:31:38 +00001568 switch (TheModule->getEndianness()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001569 case Module::LittleEndian: Out << "Module::LittleEndian);"; break;
1570 case Module::BigEndian: Out << "Module::BigEndian);"; break;
1571 case Module::AnyEndianness:Out << "Module::AnyEndianness);"; break;
Reid Spencer12803f52006-05-31 17:31:38 +00001572 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001573 nl(Out) << "mod->setPointerSize(";
Reid Spencer12803f52006-05-31 17:31:38 +00001574 switch (TheModule->getPointerSize()) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001575 case Module::Pointer32: Out << "Module::Pointer32);"; break;
1576 case Module::Pointer64: Out << "Module::Pointer64);"; break;
1577 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);"; break;
Reid Spencer12803f52006-05-31 17:31:38 +00001578 }
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001579 nl(Out);
1580 if (!TheModule->getTargetTriple().empty()) {
Reid Spencer12803f52006-05-31 17:31:38 +00001581 Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001582 << "\");";
1583 nl(Out);
1584 }
Reid Spencer12803f52006-05-31 17:31:38 +00001585
1586 if (!TheModule->getModuleInlineAsm().empty()) {
1587 Out << "mod->setModuleInlineAsm(\"";
1588 printEscapedString(TheModule->getModuleInlineAsm());
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001589 Out << "\");";
1590 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001591 }
1592
1593 // Loop over the dependent libraries and emit them.
1594 Module::lib_iterator LI = TheModule->lib_begin();
1595 Module::lib_iterator LE = TheModule->lib_end();
1596 while (LI != LE) {
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001597 Out << "mod->addLibrary(\"" << *LI << "\");";
1598 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001599 ++LI;
1600 }
1601 printModuleBody();
Reid Spencer70bbf9a2006-08-14 22:35:15 +00001602 nl(Out) << "return mod;";
1603 nl(Out,-1) << "}";
1604 nl(Out);
Reid Spencer12803f52006-05-31 17:31:38 +00001605}
1606
1607void CppWriter::printContents(
1608 const std::string& fname, // Name of generated function
1609 const std::string& mName // Name of module generated module
1610) {
1611 Out << "\nModule* " << fname << "(Module *mod) {\n";
1612 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001613 printModuleBody();
1614 Out << "\nreturn mod;\n";
1615 Out << "\n}\n";
1616}
1617
1618void CppWriter::printFunction(
1619 const std::string& fname, // Name of generated function
1620 const std::string& funcName // Name of function to generate
1621) {
1622 const Function* F = TheModule->getNamedFunction(funcName);
1623 if (!F) {
1624 error(std::string("Function '") + funcName + "' not found in input module");
1625 return;
1626 }
1627 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1628 printFunctionUses(F);
1629 printFunctionHead(F);
1630 printFunctionBody(F);
1631 Out << "return " << getCppName(F) << ";\n";
1632 Out << "}\n";
1633}
1634
1635void CppWriter::printVariable(
1636 const std::string& fname, /// Name of generated function
1637 const std::string& varName // Name of variable to generate
1638) {
1639 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1640
1641 if (!GV) {
1642 error(std::string("Variable '") + varName + "' not found in input module");
1643 return;
1644 }
1645 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1646 printVariableUses(GV);
1647 printVariableHead(GV);
1648 printVariableBody(GV);
1649 Out << "return " << getCppName(GV) << ";\n";
1650 Out << "}\n";
1651}
1652
1653void CppWriter::printType(
1654 const std::string& fname, /// Name of generated function
1655 const std::string& typeName // Name of type to generate
1656) {
1657 const Type* Ty = TheModule->getTypeByName(typeName);
1658 if (!Ty) {
1659 error(std::string("Type '") + typeName + "' not found in input module");
1660 return;
1661 }
1662 Out << "\nType* " << fname << "(Module *mod) {\n";
1663 printType(Ty);
1664 Out << "return " << getCppName(Ty) << ";\n";
1665 Out << "}\n";
1666}
1667
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001668} // end anonymous llvm
1669
1670namespace llvm {
1671
1672void WriteModuleToCppFile(Module* mod, std::ostream& o) {
Reid Spencer12803f52006-05-31 17:31:38 +00001673 // Initialize a CppWriter for us to use
1674 CppWriter W(o, mod);
1675
1676 // Emit a header
Reid Spencer25edc352006-05-31 04:43:19 +00001677 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
Reid Spencer12803f52006-05-31 17:31:38 +00001678
1679 // Get the name of the function we're supposed to generate
Reid Spencer15f7e012006-05-30 21:18:23 +00001680 std::string fname = FuncName.getValue();
Reid Spencer12803f52006-05-31 17:31:38 +00001681
1682 // Get the name of the thing we are to generate
1683 std::string tgtname = NameToGenerate.getValue();
1684 if (GenerationType == GenModule ||
1685 GenerationType == GenContents ||
1686 GenerationType == GenProgram) {
1687 if (tgtname == "!bad!") {
1688 if (mod->getModuleIdentifier() == "-")
1689 tgtname = "<stdin>";
1690 else
1691 tgtname = mod->getModuleIdentifier();
1692 }
1693 } else if (tgtname == "!bad!") {
1694 W.error("You must use the -for option with -gen-{function,variable,type}");
1695 }
1696
1697 switch (WhatToGenerate(GenerationType)) {
1698 case GenProgram:
1699 if (fname.empty())
1700 fname = "makeLLVMModule";
1701 W.printProgram(fname,tgtname);
1702 break;
1703 case GenModule:
1704 if (fname.empty())
1705 fname = "makeLLVMModule";
1706 W.printModule(fname,tgtname);
1707 break;
1708 case GenContents:
1709 if (fname.empty())
1710 fname = "makeLLVMModuleContents";
1711 W.printContents(fname,tgtname);
1712 break;
1713 case GenFunction:
1714 if (fname.empty())
1715 fname = "makeLLVMFunction";
1716 W.printFunction(fname,tgtname);
1717 break;
Reid Spencerf977e7b2006-06-01 23:43:47 +00001718 case GenInline:
1719 if (fname.empty())
1720 fname = "makeLLVMInline";
1721 W.printInline(fname,tgtname);
1722 break;
Reid Spencer12803f52006-05-31 17:31:38 +00001723 case GenVariable:
1724 if (fname.empty())
1725 fname = "makeLLVMVariable";
1726 W.printVariable(fname,tgtname);
1727 break;
1728 case GenType:
1729 if (fname.empty())
1730 fname = "makeLLVMType";
1731 W.printType(fname,tgtname);
1732 break;
1733 default:
1734 W.error("Invalid generation option");
Reid Spencer15f7e012006-05-30 21:18:23 +00001735 }
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001736}
1737
1738}