blob: a10fec00fd3b2adf48a57654d25891fb94355e8e [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- CppWriter.cpp - Printing LLVM IR as a C++ Source File -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5f5a5732007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/Module.h"
22#include "llvm/TypeSymbolTable.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/CFG.h"
28#include "llvm/Support/ManagedStatic.h"
29#include "llvm/Support/MathExtras.h"
30#include "llvm/Config/config.h"
31#include <algorithm>
32#include <iostream>
33#include <set>
34
35using namespace llvm;
36
37static cl::opt<std::string>
38FuncName("funcname", cl::desc("Specify the name of the generated function"),
39 cl::value_desc("function name"));
40
41enum WhatToGenerate {
42 GenProgram,
43 GenModule,
44 GenContents,
45 GenFunction,
Chris Lattner0366a6d2007-11-13 18:22:33 +000046 GenFunctions,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047 GenInline,
48 GenVariable,
49 GenType
50};
51
52static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
53 cl::desc("Choose what kind of output to generate"),
54 cl::init(GenProgram),
55 cl::values(
Chris Lattner0366a6d2007-11-13 18:22:33 +000056 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
57 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
58 clEnumValN(GenContents, "gen-contents", "Generate contents of a module"),
59 clEnumValN(GenFunction, "gen-function", "Generate a function definition"),
60 clEnumValN(GenFunctions,"gen-functions", "Generate all function definitions"),
61 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
62 clEnumValN(GenVariable, "gen-variable", "Generate a variable definition"),
63 clEnumValN(GenType, "gen-type", "Generate a type definition"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064 clEnumValEnd
65 )
66);
67
68static cl::opt<std::string> NameToGenerate("for", cl::Optional,
69 cl::desc("Specify the name of the thing to generate"),
70 cl::init("!bad!"));
71
72namespace {
73typedef std::vector<const Type*> TypeList;
74typedef std::map<const Type*,std::string> TypeMap;
75typedef std::map<const Value*,std::string> ValueMap;
76typedef std::set<std::string> NameSet;
77typedef std::set<const Type*> TypeSet;
78typedef std::set<const Value*> ValueSet;
79typedef std::map<const Value*,std::string> ForwardRefMap;
80
81class CppWriter {
82 const char* progname;
83 std::ostream &Out;
84 const Module *TheModule;
85 uint64_t uniqueNum;
86 TypeMap TypeNames;
87 ValueMap ValueNames;
88 TypeMap UnresolvedTypes;
89 TypeList TypeStack;
90 NameSet UsedNames;
91 TypeSet DefinedTypes;
92 ValueSet DefinedValues;
93 ForwardRefMap ForwardRefs;
94 bool is_inline;
95
96public:
97 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
98 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
99 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
100
101 const Module* getModule() { return TheModule; }
102
103 void printProgram(const std::string& fname, const std::string& modName );
104 void printModule(const std::string& fname, const std::string& modName );
105 void printContents(const std::string& fname, const std::string& modName );
106 void printFunction(const std::string& fname, const std::string& funcName );
Chris Lattner0366a6d2007-11-13 18:22:33 +0000107 void printFunctions();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108 void printInline(const std::string& fname, const std::string& funcName );
109 void printVariable(const std::string& fname, const std::string& varName );
110 void printType(const std::string& fname, const std::string& typeName );
111
112 void error(const std::string& msg);
113
114private:
115 void printLinkageType(GlobalValue::LinkageTypes LT);
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000116 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 void printCallingConv(unsigned cc);
118 void printEscapedString(const std::string& str);
119 void printCFP(const ConstantFP* CFP);
120
121 std::string getCppName(const Type* val);
122 inline void printCppName(const Type* val);
123
124 std::string getCppName(const Value* val);
125 inline void printCppName(const Value* val);
126
Chris Lattner1c8733e2008-03-12 17:45:29 +0000127 void printParamAttrs(const PAListPtr &PAL, const std::string &name);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 bool printTypeInternal(const Type* Ty);
129 inline void printType(const Type* Ty);
130 void printTypes(const Module* M);
131
132 void printConstant(const Constant *CPV);
133 void printConstants(const Module* M);
134
135 void printVariableUses(const GlobalVariable *GV);
136 void printVariableHead(const GlobalVariable *GV);
137 void printVariableBody(const GlobalVariable *GV);
138
139 void printFunctionUses(const Function *F);
140 void printFunctionHead(const Function *F);
141 void printFunctionBody(const Function *F);
142 void printInstruction(const Instruction *I, const std::string& bbname);
143 std::string getOpName(Value*);
144
145 void printModuleBody();
146
147};
148
149static unsigned indent_level = 0;
150inline std::ostream& nl(std::ostream& Out, int delta = 0) {
151 Out << "\n";
152 if (delta >= 0 || indent_level >= unsigned(-delta))
153 indent_level += delta;
154 for (unsigned i = 0; i < indent_level; ++i)
155 Out << " ";
156 return Out;
157}
158
159inline void in() { indent_level++; }
160inline void out() { if (indent_level >0) indent_level--; }
161
162inline void
163sanitize(std::string& str) {
164 for (size_t i = 0; i < str.length(); ++i)
165 if (!isalnum(str[i]) && str[i] != '_')
166 str[i] = '_';
167}
168
169inline std::string
170getTypePrefix(const Type* Ty ) {
171 switch (Ty->getTypeID()) {
172 case Type::VoidTyID: return "void_";
173 case Type::IntegerTyID:
174 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
175 "_";
176 case Type::FloatTyID: return "float_";
177 case Type::DoubleTyID: return "double_";
178 case Type::LabelTyID: return "label_";
179 case Type::FunctionTyID: return "func_";
180 case Type::StructTyID: return "struct_";
181 case Type::ArrayTyID: return "array_";
182 case Type::PointerTyID: return "ptr_";
183 case Type::VectorTyID: return "packed_";
184 case Type::OpaqueTyID: return "opaque_";
185 default: return "other_";
186 }
187 return "unknown_";
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 TypeSymbolTable& ST, const Type* Ty)
196{
197 TypeSymbolTable::const_iterator TI = ST.begin();
198 TypeSymbolTable::const_iterator TE = ST.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
211// 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) {
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000216 APFloat APF = APFloat(CFP->getValueAPF()); // copy
217 if (CFP->getType() == Type::FloatTy)
218 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 Out << "ConstantFP::get(";
220 if (CFP->getType() == Type::DoubleTy)
221 Out << "Type::DoubleTy, ";
222 else
223 Out << "Type::FloatTy, ";
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000224 Out << "APFloat(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225#if HAVE_PRINTF_A
226 char Buffer[100];
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000227 sprintf(Buffer, "%A", APF.convertToDouble());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 if ((!strncmp(Buffer, "0x", 2) ||
229 !strncmp(Buffer, "-0x", 3) ||
230 !strncmp(Buffer, "+0x", 3)) &&
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000231 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 if (CFP->getType() == Type::DoubleTy)
233 Out << "BitsToDouble(" << Buffer << ")";
234 else
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000235 Out << "BitsToFloat((float)" << Buffer << ")";
236 Out << ")";
237 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238#endif
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000239 std::string StrVal = ftostr(CFP->getValueAPF());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240
241 while (StrVal[0] == ' ')
242 StrVal.erase(StrVal.begin());
243
244 // Check to make sure that the stringized number is not some string like
245 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
246 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
247 ((StrVal[0] == '-' || StrVal[0] == '+') &&
248 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000249 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 if (CFP->getType() == Type::DoubleTy)
251 Out << StrVal;
252 else
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000253 Out << StrVal << "f";
254 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 else if (CFP->getType() == Type::DoubleTy)
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000256 Out << "BitsToDouble(0x" << std::hex
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000257 << CFP->getValueAPF().convertToAPInt().getZExtValue()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258 << std::dec << "ULL) /* " << StrVal << " */";
259 else
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000260 Out << "BitsToFloat(0x" << std::hex
Dale Johannesenfbd9cda2007-09-12 03:30:33 +0000261 << (uint32_t)CFP->getValueAPF().convertToAPInt().getZExtValue()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 << std::dec << "U) /* " << StrVal << " */";
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000263 Out << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264#if HAVE_PRINTF_A
265 }
266#endif
267 Out << ")";
268}
269
270void
271CppWriter::printCallingConv(unsigned cc){
272 // Print the calling convention.
273 switch (cc) {
274 case CallingConv::C: Out << "CallingConv::C"; break;
275 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
276 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
277 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
278 default: Out << cc; break;
279 }
280}
281
282void
283CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
284 switch (LT) {
285 case GlobalValue::InternalLinkage:
286 Out << "GlobalValue::InternalLinkage"; break;
287 case GlobalValue::LinkOnceLinkage:
288 Out << "GlobalValue::LinkOnceLinkage "; break;
289 case GlobalValue::WeakLinkage:
290 Out << "GlobalValue::WeakLinkage"; break;
291 case GlobalValue::AppendingLinkage:
292 Out << "GlobalValue::AppendingLinkage"; break;
293 case GlobalValue::ExternalLinkage:
294 Out << "GlobalValue::ExternalLinkage"; break;
295 case GlobalValue::DLLImportLinkage:
296 Out << "GlobalValue::DLLImportLinkage"; break;
297 case GlobalValue::DLLExportLinkage:
298 Out << "GlobalValue::DLLExportLinkage"; break;
299 case GlobalValue::ExternalWeakLinkage:
300 Out << "GlobalValue::ExternalWeakLinkage"; break;
301 case GlobalValue::GhostLinkage:
302 Out << "GlobalValue::GhostLinkage"; break;
303 }
304}
305
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000306void
307CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
308 switch (VisType) {
309 default: assert(0 && "Unknown GVar visibility");
310 case GlobalValue::DefaultVisibility:
311 Out << "GlobalValue::DefaultVisibility";
312 break;
313 case GlobalValue::HiddenVisibility:
314 Out << "GlobalValue::HiddenVisibility";
315 break;
316 case GlobalValue::ProtectedVisibility:
317 Out << "GlobalValue::ProtectedVisibility";
318 break;
319 }
320}
321
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322// printEscapedString - Print each character of the specified string, escaping
323// it if it is not printable or if it is an escape char.
324void
325CppWriter::printEscapedString(const std::string &Str) {
326 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
327 unsigned char C = Str[i];
328 if (isprint(C) && C != '"' && C != '\\') {
329 Out << C;
330 } else {
331 Out << "\\x"
332 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
333 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
334 }
335 }
336}
337
338std::string
339CppWriter::getCppName(const Type* Ty)
340{
341 // First, handle the primitive types .. easy
342 if (Ty->isPrimitiveType() || Ty->isInteger()) {
343 switch (Ty->getTypeID()) {
344 case Type::VoidTyID: return "Type::VoidTy";
345 case Type::IntegerTyID: {
346 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
347 return "IntegerType::get(" + utostr(BitWidth) + ")";
348 }
349 case Type::FloatTyID: return "Type::FloatTy";
350 case Type::DoubleTyID: return "Type::DoubleTy";
351 case Type::LabelTyID: return "Type::LabelTy";
352 default:
353 error("Invalid primitive type");
354 break;
355 }
356 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
357 }
358
359 // Now, see if we've seen the type before and return that
360 TypeMap::iterator I = TypeNames.find(Ty);
361 if (I != TypeNames.end())
362 return I->second;
363
364 // Okay, let's build a new name for this type. Start with a prefix
365 const char* prefix = 0;
366 switch (Ty->getTypeID()) {
367 case Type::FunctionTyID: prefix = "FuncTy_"; break;
368 case Type::StructTyID: prefix = "StructTy_"; break;
369 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
370 case Type::PointerTyID: prefix = "PointerTy_"; break;
371 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
372 case Type::VectorTyID: prefix = "VectorTy_"; break;
373 default: prefix = "OtherTy_"; break; // prevent breakage
374 }
375
376 // See if the type has a name in the symboltable and build accordingly
377 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
378 std::string name;
379 if (tName)
380 name = std::string(prefix) + *tName;
381 else
382 name = std::string(prefix) + utostr(uniqueNum++);
383 sanitize(name);
384
385 // Save the name
386 return TypeNames[Ty] = name;
387}
388
389void
390CppWriter::printCppName(const Type* Ty)
391{
392 printEscapedString(getCppName(Ty));
393}
394
395std::string
396CppWriter::getCppName(const Value* val) {
397 std::string name;
398 ValueMap::iterator I = ValueNames.find(val);
399 if (I != ValueNames.end() && I->first == val)
400 return I->second;
401
402 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
403 name = std::string("gvar_") +
404 getTypePrefix(GV->getType()->getElementType());
405 } else if (isa<Function>(val)) {
406 name = std::string("func_");
407 } else if (const Constant* C = dyn_cast<Constant>(val)) {
408 name = std::string("const_") + getTypePrefix(C->getType());
409 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
410 if (is_inline) {
411 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
412 Function::const_arg_iterator(Arg)) + 1;
413 name = std::string("arg_") + utostr(argNum);
414 NameSet::iterator NI = UsedNames.find(name);
415 if (NI != UsedNames.end())
416 name += std::string("_") + utostr(uniqueNum++);
417 UsedNames.insert(name);
418 return ValueNames[val] = name;
419 } else {
420 name = getTypePrefix(val->getType());
421 }
422 } else {
423 name = getTypePrefix(val->getType());
424 }
425 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
426 sanitize(name);
427 NameSet::iterator NI = UsedNames.find(name);
428 if (NI != UsedNames.end())
429 name += std::string("_") + utostr(uniqueNum++);
430 UsedNames.insert(name);
431 return ValueNames[val] = name;
432}
433
434void
435CppWriter::printCppName(const Value* val) {
436 printEscapedString(getCppName(val));
437}
438
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000439void
Chris Lattner1c8733e2008-03-12 17:45:29 +0000440CppWriter::printParamAttrs(const PAListPtr &PAL, const std::string &name) {
441 Out << "PAListPtr " << name << "_PAL = 0;";
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000442 nl(Out);
Chris Lattner1c8733e2008-03-12 17:45:29 +0000443 if (!PAL.isEmpty()) {
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000444 Out << '{'; in(); nl(Out);
Chris Lattner1c8733e2008-03-12 17:45:29 +0000445 Out << "SmallVector<ParamAttrsWithIndex, 4> Attrs;"; nl(Out);
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000446 Out << "ParamAttrsWithIndex PAWI;"; nl(Out);
Chris Lattner1c8733e2008-03-12 17:45:29 +0000447 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
448 uint16_t index = PAL.getSlot(i).Index;
449 ParameterAttributes attrs = PAL.getSlot(i).Attrs;
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000450 Out << "PAWI.index = " << index << "; PAWI.attrs = 0 ";
451 if (attrs & ParamAttr::SExt)
452 Out << " | ParamAttr::SExt";
453 if (attrs & ParamAttr::ZExt)
454 Out << " | ParamAttr::ZExt";
455 if (attrs & ParamAttr::StructRet)
456 Out << " | ParamAttr::StructRet";
457 if (attrs & ParamAttr::InReg)
458 Out << " | ParamAttr::InReg";
459 if (attrs & ParamAttr::NoReturn)
460 Out << " | ParamAttr::NoReturn";
461 if (attrs & ParamAttr::NoUnwind)
462 Out << " | ParamAttr::NoUnwind";
463 Out << ";";
464 nl(Out);
465 Out << "Attrs.push_back(PAWI);";
466 nl(Out);
467 }
Chris Lattner1c8733e2008-03-12 17:45:29 +0000468 Out << name << "_PAL = PAListPtr::get(Attrs.begin(), Attrs.end());";
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000469 nl(Out);
470 out(); nl(Out);
471 Out << '}'; nl(Out);
472 }
473}
474
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000475bool
476CppWriter::printTypeInternal(const Type* Ty) {
477 // We don't print definitions for primitive types
478 if (Ty->isPrimitiveType() || Ty->isInteger())
479 return false;
480
481 // If we already defined this type, we don't need to define it again.
482 if (DefinedTypes.find(Ty) != DefinedTypes.end())
483 return false;
484
485 // Everything below needs the name for the type so get it now.
486 std::string typeName(getCppName(Ty));
487
488 // Search the type stack for recursion. If we find it, then generate this
489 // as an OpaqueType, but make sure not to do this multiple times because
490 // the type could appear in multiple places on the stack. Once the opaque
491 // definition is issued, it must not be re-issued. Consequently we have to
492 // check the UnresolvedTypes list as well.
493 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
494 if (TI != TypeStack.end()) {
495 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
496 if (I == UnresolvedTypes.end()) {
497 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
498 nl(Out);
499 UnresolvedTypes[Ty] = typeName;
500 }
501 return true;
502 }
503
504 // We're going to print a derived type which, by definition, contains other
505 // types. So, push this one we're printing onto the type stack to assist with
506 // recursive definitions.
507 TypeStack.push_back(Ty);
508
509 // Print the type definition
510 switch (Ty->getTypeID()) {
511 case Type::FunctionTyID: {
512 const FunctionType* FT = cast<FunctionType>(Ty);
513 Out << "std::vector<const Type*>" << typeName << "_args;";
514 nl(Out);
515 FunctionType::param_iterator PI = FT->param_begin();
516 FunctionType::param_iterator PE = FT->param_end();
517 for (; PI != PE; ++PI) {
518 const Type* argTy = static_cast<const Type*>(*PI);
519 bool isForward = printTypeInternal(argTy);
520 std::string argName(getCppName(argTy));
521 Out << typeName << "_args.push_back(" << argName;
522 if (isForward)
523 Out << "_fwd";
524 Out << ");";
525 nl(Out);
526 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527 bool isForward = printTypeInternal(FT->getReturnType());
528 std::string retTypeName(getCppName(FT->getReturnType()));
529 Out << "FunctionType* " << typeName << " = FunctionType::get(";
530 in(); nl(Out) << "/*Result=*/" << retTypeName;
531 if (isForward)
532 Out << "_fwd";
533 Out << ",";
534 nl(Out) << "/*Params=*/" << typeName << "_args,";
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000535 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 out();
537 nl(Out);
538 break;
539 }
540 case Type::StructTyID: {
541 const StructType* ST = cast<StructType>(Ty);
542 Out << "std::vector<const Type*>" << typeName << "_fields;";
543 nl(Out);
544 StructType::element_iterator EI = ST->element_begin();
545 StructType::element_iterator EE = ST->element_end();
546 for (; EI != EE; ++EI) {
547 const Type* fieldTy = static_cast<const Type*>(*EI);
548 bool isForward = printTypeInternal(fieldTy);
549 std::string fieldName(getCppName(fieldTy));
550 Out << typeName << "_fields.push_back(" << fieldName;
551 if (isForward)
552 Out << "_fwd";
553 Out << ");";
554 nl(Out);
555 }
556 Out << "StructType* " << typeName << " = StructType::get("
557 << typeName << "_fields, /*isPacked=*/"
558 << (ST->isPacked() ? "true" : "false") << ");";
559 nl(Out);
560 break;
561 }
562 case Type::ArrayTyID: {
563 const ArrayType* AT = cast<ArrayType>(Ty);
564 const Type* ET = AT->getElementType();
565 bool isForward = printTypeInternal(ET);
566 std::string elemName(getCppName(ET));
567 Out << "ArrayType* " << typeName << " = ArrayType::get("
568 << elemName << (isForward ? "_fwd" : "")
569 << ", " << utostr(AT->getNumElements()) << ");";
570 nl(Out);
571 break;
572 }
573 case Type::PointerTyID: {
574 const PointerType* PT = cast<PointerType>(Ty);
575 const Type* ET = PT->getElementType();
576 bool isForward = printTypeInternal(ET);
577 std::string elemName(getCppName(ET));
578 Out << "PointerType* " << typeName << " = PointerType::get("
Christopher Lambbb2f2222007-12-17 01:12:55 +0000579 << elemName << (isForward ? "_fwd" : "")
580 << ", " << utostr(PT->getAddressSpace()) << ");";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000581 nl(Out);
582 break;
583 }
584 case Type::VectorTyID: {
585 const VectorType* PT = cast<VectorType>(Ty);
586 const Type* ET = PT->getElementType();
587 bool isForward = printTypeInternal(ET);
588 std::string elemName(getCppName(ET));
589 Out << "VectorType* " << typeName << " = VectorType::get("
590 << elemName << (isForward ? "_fwd" : "")
591 << ", " << utostr(PT->getNumElements()) << ");";
592 nl(Out);
593 break;
594 }
595 case Type::OpaqueTyID: {
596 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
597 nl(Out);
598 break;
599 }
600 default:
601 error("Invalid TypeID");
602 }
603
604 // If the type had a name, make sure we recreate it.
605 const std::string* progTypeName =
606 findTypeName(TheModule->getTypeSymbolTable(),Ty);
607 if (progTypeName) {
608 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
609 << typeName << ");";
610 nl(Out);
611 }
612
613 // Pop us off the type stack
614 TypeStack.pop_back();
615
616 // Indicate that this type is now defined.
617 DefinedTypes.insert(Ty);
618
619 // Early resolve as many unresolved types as possible. Search the unresolved
620 // types map for the type we just printed. Now that its definition is complete
621 // we can resolve any previous references to it. This prevents a cascade of
622 // unresolved types.
623 TypeMap::iterator I = UnresolvedTypes.find(Ty);
624 if (I != UnresolvedTypes.end()) {
625 Out << "cast<OpaqueType>(" << I->second
626 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
627 nl(Out);
628 Out << I->second << " = cast<";
629 switch (Ty->getTypeID()) {
630 case Type::FunctionTyID: Out << "FunctionType"; break;
631 case Type::ArrayTyID: Out << "ArrayType"; break;
632 case Type::StructTyID: Out << "StructType"; break;
633 case Type::VectorTyID: Out << "VectorType"; break;
634 case Type::PointerTyID: Out << "PointerType"; break;
635 case Type::OpaqueTyID: Out << "OpaqueType"; break;
636 default: Out << "NoSuchDerivedType"; break;
637 }
638 Out << ">(" << I->second << "_fwd.get());";
639 nl(Out); nl(Out);
640 UnresolvedTypes.erase(I);
641 }
642
643 // Finally, separate the type definition from other with a newline.
644 nl(Out);
645
646 // We weren't a recursive type
647 return false;
648}
649
650// Prints a type definition. Returns true if it could not resolve all the types
651// in the definition but had to use a forward reference.
652void
653CppWriter::printType(const Type* Ty) {
654 assert(TypeStack.empty());
655 TypeStack.clear();
656 printTypeInternal(Ty);
657 assert(TypeStack.empty());
658}
659
660void
661CppWriter::printTypes(const Module* M) {
662
663 // Walk the symbol table and print out all its types
664 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
665 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
666 TI != TE; ++TI) {
667
668 // For primitive types and types already defined, just add a name
669 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
670 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
671 TNI != TypeNames.end()) {
672 Out << "mod->addTypeName(\"";
673 printEscapedString(TI->first);
674 Out << "\", " << getCppName(TI->second) << ");";
675 nl(Out);
676 // For everything else, define the type
677 } else {
678 printType(TI->second);
679 }
680 }
681
682 // Add all of the global variables to the value table...
683 for (Module::const_global_iterator I = TheModule->global_begin(),
684 E = TheModule->global_end(); I != E; ++I) {
685 if (I->hasInitializer())
686 printType(I->getInitializer()->getType());
687 printType(I->getType());
688 }
689
690 // Add all the functions to the table
691 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
692 FI != FE; ++FI) {
693 printType(FI->getReturnType());
694 printType(FI->getFunctionType());
695 // Add all the function arguments
696 for(Function::const_arg_iterator AI = FI->arg_begin(),
697 AE = FI->arg_end(); AI != AE; ++AI) {
698 printType(AI->getType());
699 }
700
701 // Add all of the basic blocks and instructions
702 for (Function::const_iterator BB = FI->begin(),
703 E = FI->end(); BB != E; ++BB) {
704 printType(BB->getType());
705 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
706 ++I) {
707 printType(I->getType());
708 for (unsigned i = 0; i < I->getNumOperands(); ++i)
709 printType(I->getOperand(i)->getType());
710 }
711 }
712 }
713}
714
715
716// printConstant - Print out a constant pool entry...
717void CppWriter::printConstant(const Constant *CV) {
718 // First, if the constant is actually a GlobalValue (variable or function) or
719 // its already in the constant list then we've printed it already and we can
720 // just return.
721 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
722 return;
723
724 std::string constName(getCppName(CV));
725 std::string typeName(getCppName(CV->getType()));
726 if (CV->isNullValue()) {
727 Out << "Constant* " << constName << " = Constant::getNullValue("
728 << typeName << ");";
729 nl(Out);
730 return;
731 }
732 if (isa<GlobalValue>(CV)) {
733 // Skip variables and functions, we emit them elsewhere
734 return;
735 }
736 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
737 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
738 << cast<IntegerType>(CI->getType())->getBitWidth() << ", "
739 << " \"" << CI->getValue().toStringSigned(10) << "\", 10));";
740 } else if (isa<ConstantAggregateZero>(CV)) {
741 Out << "ConstantAggregateZero* " << constName
742 << " = ConstantAggregateZero::get(" << typeName << ");";
743 } else if (isa<ConstantPointerNull>(CV)) {
744 Out << "ConstantPointerNull* " << constName
745 << " = ConstanPointerNull::get(" << typeName << ");";
746 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
747 Out << "ConstantFP* " << constName << " = ";
748 printCFP(CFP);
749 Out << ";";
750 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
751 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
752 Out << "Constant* " << constName << " = ConstantArray::get(\"";
753 std::string tmp = CA->getAsString();
754 bool nullTerminate = false;
755 if (tmp[tmp.length()-1] == 0) {
756 tmp.erase(tmp.length()-1);
757 nullTerminate = true;
758 }
759 printEscapedString(tmp);
760 // Determine if we want null termination or not.
761 if (nullTerminate)
762 Out << "\", true"; // Indicate that the null terminator should be added.
763 else
764 Out << "\", false";// No null terminator
765 Out << ");";
766 } else {
767 Out << "std::vector<Constant*> " << constName << "_elems;";
768 nl(Out);
769 unsigned N = CA->getNumOperands();
770 for (unsigned i = 0; i < N; ++i) {
771 printConstant(CA->getOperand(i)); // recurse to print operands
772 Out << constName << "_elems.push_back("
773 << getCppName(CA->getOperand(i)) << ");";
774 nl(Out);
775 }
776 Out << "Constant* " << constName << " = ConstantArray::get("
777 << typeName << ", " << constName << "_elems);";
778 }
779 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
780 Out << "std::vector<Constant*> " << constName << "_fields;";
781 nl(Out);
782 unsigned N = CS->getNumOperands();
783 for (unsigned i = 0; i < N; i++) {
784 printConstant(CS->getOperand(i));
785 Out << constName << "_fields.push_back("
786 << getCppName(CS->getOperand(i)) << ");";
787 nl(Out);
788 }
789 Out << "Constant* " << constName << " = ConstantStruct::get("
790 << typeName << ", " << constName << "_fields);";
791 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
792 Out << "std::vector<Constant*> " << constName << "_elems;";
793 nl(Out);
794 unsigned N = CP->getNumOperands();
795 for (unsigned i = 0; i < N; ++i) {
796 printConstant(CP->getOperand(i));
797 Out << constName << "_elems.push_back("
798 << getCppName(CP->getOperand(i)) << ");";
799 nl(Out);
800 }
801 Out << "Constant* " << constName << " = ConstantVector::get("
802 << typeName << ", " << constName << "_elems);";
803 } else if (isa<UndefValue>(CV)) {
804 Out << "UndefValue* " << constName << " = UndefValue::get("
805 << typeName << ");";
806 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
807 if (CE->getOpcode() == Instruction::GetElementPtr) {
808 Out << "std::vector<Constant*> " << constName << "_indices;";
809 nl(Out);
810 printConstant(CE->getOperand(0));
811 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
812 printConstant(CE->getOperand(i));
813 Out << constName << "_indices.push_back("
814 << getCppName(CE->getOperand(i)) << ");";
815 nl(Out);
816 }
817 Out << "Constant* " << constName
818 << " = ConstantExpr::getGetElementPtr("
819 << getCppName(CE->getOperand(0)) << ", "
David Greene69fc0d52007-09-04 17:15:07 +0000820 << "&" << constName << "_indices[0], "
821 << constName << "_indices.size()"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000822 << " );";
823 } else if (CE->isCast()) {
824 printConstant(CE->getOperand(0));
825 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
826 switch (CE->getOpcode()) {
827 default: assert(0 && "Invalid cast opcode");
828 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
829 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
830 case Instruction::SExt: Out << "Instruction::SExt"; break;
831 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
832 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
833 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
834 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
835 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
836 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
837 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
838 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
839 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
840 }
841 Out << ", " << getCppName(CE->getOperand(0)) << ", "
842 << getCppName(CE->getType()) << ");";
843 } else {
844 unsigned N = CE->getNumOperands();
845 for (unsigned i = 0; i < N; ++i ) {
846 printConstant(CE->getOperand(i));
847 }
848 Out << "Constant* " << constName << " = ConstantExpr::";
849 switch (CE->getOpcode()) {
850 case Instruction::Add: Out << "getAdd("; break;
851 case Instruction::Sub: Out << "getSub("; break;
852 case Instruction::Mul: Out << "getMul("; break;
853 case Instruction::UDiv: Out << "getUDiv("; break;
854 case Instruction::SDiv: Out << "getSDiv("; break;
855 case Instruction::FDiv: Out << "getFDiv("; break;
856 case Instruction::URem: Out << "getURem("; break;
857 case Instruction::SRem: Out << "getSRem("; break;
858 case Instruction::FRem: Out << "getFRem("; break;
859 case Instruction::And: Out << "getAnd("; break;
860 case Instruction::Or: Out << "getOr("; break;
861 case Instruction::Xor: Out << "getXor("; break;
862 case Instruction::ICmp:
863 Out << "getICmp(ICmpInst::ICMP_";
864 switch (CE->getPredicate()) {
865 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
866 case ICmpInst::ICMP_NE: Out << "NE"; break;
867 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
868 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
869 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
870 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
871 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
872 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
873 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
874 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
875 default: error("Invalid ICmp Predicate");
876 }
877 break;
878 case Instruction::FCmp:
879 Out << "getFCmp(FCmpInst::FCMP_";
880 switch (CE->getPredicate()) {
881 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
882 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
883 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
884 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
885 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
886 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
887 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
888 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
889 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
890 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
891 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
892 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
893 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
894 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
895 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
896 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
897 default: error("Invalid FCmp Predicate");
898 }
899 break;
900 case Instruction::Shl: Out << "getShl("; break;
901 case Instruction::LShr: Out << "getLShr("; break;
902 case Instruction::AShr: Out << "getAShr("; break;
903 case Instruction::Select: Out << "getSelect("; break;
904 case Instruction::ExtractElement: Out << "getExtractElement("; break;
905 case Instruction::InsertElement: Out << "getInsertElement("; break;
906 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
907 default:
908 error("Invalid constant expression");
909 break;
910 }
911 Out << getCppName(CE->getOperand(0));
912 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
913 Out << ", " << getCppName(CE->getOperand(i));
914 Out << ");";
915 }
916 } else {
917 error("Bad Constant");
918 Out << "Constant* " << constName << " = 0; ";
919 }
920 nl(Out);
921}
922
923void
924CppWriter::printConstants(const Module* M) {
925 // Traverse all the global variables looking for constant initializers
926 for (Module::const_global_iterator I = TheModule->global_begin(),
927 E = TheModule->global_end(); I != E; ++I)
928 if (I->hasInitializer())
929 printConstant(I->getInitializer());
930
931 // Traverse the LLVM functions looking for constants
932 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
933 FI != FE; ++FI) {
934 // Add all of the basic blocks and instructions
935 for (Function::const_iterator BB = FI->begin(),
936 E = FI->end(); BB != E; ++BB) {
937 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
938 ++I) {
939 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
940 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
941 printConstant(C);
942 }
943 }
944 }
945 }
946 }
947}
948
949void CppWriter::printVariableUses(const GlobalVariable *GV) {
950 nl(Out) << "// Type Definitions";
951 nl(Out);
952 printType(GV->getType());
953 if (GV->hasInitializer()) {
954 Constant* Init = GV->getInitializer();
955 printType(Init->getType());
956 if (Function* F = dyn_cast<Function>(Init)) {
957 nl(Out)<< "/ Function Declarations"; nl(Out);
958 printFunctionHead(F);
959 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
960 nl(Out) << "// Global Variable Declarations"; nl(Out);
961 printVariableHead(gv);
962 } else {
963 nl(Out) << "// Constant Definitions"; nl(Out);
964 printConstant(gv);
965 }
966 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
967 nl(Out) << "// Global Variable Definitions"; nl(Out);
968 printVariableBody(gv);
969 }
970 }
971}
972
973void CppWriter::printVariableHead(const GlobalVariable *GV) {
974 nl(Out) << "GlobalVariable* " << getCppName(GV);
975 if (is_inline) {
976 Out << " = mod->getGlobalVariable(";
977 printEscapedString(GV->getName());
978 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
979 nl(Out) << "if (!" << getCppName(GV) << ") {";
980 in(); nl(Out) << getCppName(GV);
981 }
982 Out << " = new GlobalVariable(";
983 nl(Out) << "/*Type=*/";
984 printCppName(GV->getType()->getElementType());
985 Out << ",";
986 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
987 Out << ",";
988 nl(Out) << "/*Linkage=*/";
989 printLinkageType(GV->getLinkage());
990 Out << ",";
991 nl(Out) << "/*Initializer=*/0, ";
992 if (GV->hasInitializer()) {
993 Out << "// has initializer, specified below";
994 }
995 nl(Out) << "/*Name=*/\"";
996 printEscapedString(GV->getName());
997 Out << "\",";
998 nl(Out) << "mod);";
999 nl(Out);
1000
1001 if (GV->hasSection()) {
1002 printCppName(GV);
1003 Out << "->setSection(\"";
1004 printEscapedString(GV->getSection());
1005 Out << "\");";
1006 nl(Out);
1007 }
1008 if (GV->getAlignment()) {
1009 printCppName(GV);
1010 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1011 nl(Out);
1012 };
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001013 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1014 printCppName(GV);
1015 Out << "->setVisibility(";
1016 printVisibilityType(GV->getVisibility());
1017 Out << ");";
1018 nl(Out);
1019 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 if (is_inline) {
1021 out(); Out << "}"; nl(Out);
1022 }
1023}
1024
1025void
1026CppWriter::printVariableBody(const GlobalVariable *GV) {
1027 if (GV->hasInitializer()) {
1028 printCppName(GV);
1029 Out << "->setInitializer(";
1030 //if (!isa<GlobalValue(GV->getInitializer()))
1031 //else
1032 Out << getCppName(GV->getInitializer()) << ");";
1033 nl(Out);
1034 }
1035}
1036
1037std::string
1038CppWriter::getOpName(Value* V) {
1039 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1040 return getCppName(V);
1041
1042 // See if its alread in the map of forward references, if so just return the
1043 // name we already set up for it
1044 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1045 if (I != ForwardRefs.end())
1046 return I->second;
1047
1048 // This is a new forward reference. Generate a unique name for it
1049 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1050
1051 // Yes, this is a hack. An Argument is the smallest instantiable value that
1052 // we can make as a placeholder for the real value. We'll replace these
1053 // Argument instances later.
1054 Out << "Argument* " << result << " = new Argument("
1055 << getCppName(V->getType()) << ");";
1056 nl(Out);
1057 ForwardRefs[V] = result;
1058 return result;
1059}
1060
1061// printInstruction - This member is called for each Instruction in a function.
1062void
1063CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
1064 std::string iName(getCppName(I));
1065
1066 // Before we emit this instruction, we need to take care of generating any
1067 // forward references. So, we get the names of all the operands in advance
1068 std::string* opNames = new std::string[I->getNumOperands()];
1069 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1070 opNames[i] = getOpName(I->getOperand(i));
1071 }
1072
1073 switch (I->getOpcode()) {
1074 case Instruction::Ret: {
1075 const ReturnInst* ret = cast<ReturnInst>(I);
1076 Out << "new ReturnInst("
1077 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1078 break;
1079 }
1080 case Instruction::Br: {
1081 const BranchInst* br = cast<BranchInst>(I);
1082 Out << "new BranchInst(" ;
1083 if (br->getNumOperands() == 3 ) {
1084 Out << opNames[0] << ", "
1085 << opNames[1] << ", "
1086 << opNames[2] << ", ";
1087
1088 } else if (br->getNumOperands() == 1) {
1089 Out << opNames[0] << ", ";
1090 } else {
1091 error("Branch with 2 operands?");
1092 }
1093 Out << bbname << ");";
1094 break;
1095 }
1096 case Instruction::Switch: {
1097 const SwitchInst* sw = cast<SwitchInst>(I);
1098 Out << "SwitchInst* " << iName << " = new SwitchInst("
1099 << opNames[0] << ", "
1100 << opNames[1] << ", "
1101 << sw->getNumCases() << ", " << bbname << ");";
1102 nl(Out);
1103 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1104 Out << iName << "->addCase("
1105 << opNames[i] << ", "
1106 << opNames[i+1] << ");";
1107 nl(Out);
1108 }
1109 break;
1110 }
1111 case Instruction::Invoke: {
1112 const InvokeInst* inv = cast<InvokeInst>(I);
1113 Out << "std::vector<Value*> " << iName << "_params;";
1114 nl(Out);
1115 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1116 Out << iName << "_params.push_back("
1117 << opNames[i] << ");";
1118 nl(Out);
1119 }
1120 Out << "InvokeInst *" << iName << " = new InvokeInst("
1121 << opNames[0] << ", "
1122 << opNames[1] << ", "
1123 << opNames[2] << ", "
David Greene8278ef52007-08-27 19:04:21 +00001124 << iName << "_params.begin(), " << iName << "_params.end(), \"";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001125 printEscapedString(inv->getName());
1126 Out << "\", " << bbname << ");";
1127 nl(Out) << iName << "->setCallingConv(";
1128 printCallingConv(inv->getCallingConv());
1129 Out << ");";
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001130 printParamAttrs(inv->getParamAttrs(), iName);
1131 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1132 nl(Out);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133 break;
1134 }
1135 case Instruction::Unwind: {
1136 Out << "new UnwindInst("
1137 << bbname << ");";
1138 break;
1139 }
1140 case Instruction::Unreachable:{
1141 Out << "new UnreachableInst("
1142 << bbname << ");";
1143 break;
1144 }
1145 case Instruction::Add:
1146 case Instruction::Sub:
1147 case Instruction::Mul:
1148 case Instruction::UDiv:
1149 case Instruction::SDiv:
1150 case Instruction::FDiv:
1151 case Instruction::URem:
1152 case Instruction::SRem:
1153 case Instruction::FRem:
1154 case Instruction::And:
1155 case Instruction::Or:
1156 case Instruction::Xor:
1157 case Instruction::Shl:
1158 case Instruction::LShr:
1159 case Instruction::AShr:{
1160 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1161 switch (I->getOpcode()) {
1162 case Instruction::Add: Out << "Instruction::Add"; break;
1163 case Instruction::Sub: Out << "Instruction::Sub"; break;
1164 case Instruction::Mul: Out << "Instruction::Mul"; break;
1165 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1166 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1167 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1168 case Instruction::URem:Out << "Instruction::URem"; break;
1169 case Instruction::SRem:Out << "Instruction::SRem"; break;
1170 case Instruction::FRem:Out << "Instruction::FRem"; break;
1171 case Instruction::And: Out << "Instruction::And"; break;
1172 case Instruction::Or: Out << "Instruction::Or"; break;
1173 case Instruction::Xor: Out << "Instruction::Xor"; break;
1174 case Instruction::Shl: Out << "Instruction::Shl"; break;
1175 case Instruction::LShr:Out << "Instruction::LShr"; break;
1176 case Instruction::AShr:Out << "Instruction::AShr"; break;
1177 default: Out << "Instruction::BadOpCode"; break;
1178 }
1179 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1180 printEscapedString(I->getName());
1181 Out << "\", " << bbname << ");";
1182 break;
1183 }
1184 case Instruction::FCmp: {
1185 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1186 switch (cast<FCmpInst>(I)->getPredicate()) {
1187 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1188 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1189 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1190 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1191 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1192 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1193 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1194 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1195 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1196 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1197 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1198 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1199 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1200 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1201 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1202 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1203 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1204 }
1205 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1206 printEscapedString(I->getName());
1207 Out << "\", " << bbname << ");";
1208 break;
1209 }
1210 case Instruction::ICmp: {
1211 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1212 switch (cast<ICmpInst>(I)->getPredicate()) {
1213 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1214 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1215 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1216 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1217 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1218 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1219 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1220 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1221 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1222 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1223 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1224 }
1225 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1226 printEscapedString(I->getName());
1227 Out << "\", " << bbname << ");";
1228 break;
1229 }
1230 case Instruction::Malloc: {
1231 const MallocInst* mallocI = cast<MallocInst>(I);
1232 Out << "MallocInst* " << iName << " = new MallocInst("
1233 << getCppName(mallocI->getAllocatedType()) << ", ";
1234 if (mallocI->isArrayAllocation())
1235 Out << opNames[0] << ", " ;
1236 Out << "\"";
1237 printEscapedString(mallocI->getName());
1238 Out << "\", " << bbname << ");";
1239 if (mallocI->getAlignment())
1240 nl(Out) << iName << "->setAlignment("
1241 << mallocI->getAlignment() << ");";
1242 break;
1243 }
1244 case Instruction::Free: {
1245 Out << "FreeInst* " << iName << " = new FreeInst("
1246 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1247 break;
1248 }
1249 case Instruction::Alloca: {
1250 const AllocaInst* allocaI = cast<AllocaInst>(I);
1251 Out << "AllocaInst* " << iName << " = new AllocaInst("
1252 << getCppName(allocaI->getAllocatedType()) << ", ";
1253 if (allocaI->isArrayAllocation())
1254 Out << opNames[0] << ", ";
1255 Out << "\"";
1256 printEscapedString(allocaI->getName());
1257 Out << "\", " << bbname << ");";
1258 if (allocaI->getAlignment())
1259 nl(Out) << iName << "->setAlignment("
1260 << allocaI->getAlignment() << ");";
1261 break;
1262 }
1263 case Instruction::Load:{
1264 const LoadInst* load = cast<LoadInst>(I);
1265 Out << "LoadInst* " << iName << " = new LoadInst("
1266 << opNames[0] << ", \"";
1267 printEscapedString(load->getName());
1268 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1269 << ", " << bbname << ");";
1270 break;
1271 }
1272 case Instruction::Store: {
1273 const StoreInst* store = cast<StoreInst>(I);
1274 Out << "StoreInst* " << iName << " = new StoreInst("
1275 << opNames[0] << ", "
1276 << opNames[1] << ", "
1277 << (store->isVolatile() ? "true" : "false")
1278 << ", " << bbname << ");";
1279 break;
1280 }
1281 case Instruction::GetElementPtr: {
1282 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1283 if (gep->getNumOperands() <= 2) {
1284 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1285 << opNames[0];
1286 if (gep->getNumOperands() == 2)
1287 Out << ", " << opNames[1];
1288 } else {
1289 Out << "std::vector<Value*> " << iName << "_indices;";
1290 nl(Out);
1291 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1292 Out << iName << "_indices.push_back("
1293 << opNames[i] << ");";
1294 nl(Out);
1295 }
1296 Out << "Instruction* " << iName << " = new GetElementPtrInst("
David Greene393be882007-09-04 15:46:09 +00001297 << opNames[0] << ", " << iName << "_indices.begin(), "
1298 << iName << "_indices.end()";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299 }
1300 Out << ", \"";
1301 printEscapedString(gep->getName());
1302 Out << "\", " << bbname << ");";
1303 break;
1304 }
1305 case Instruction::PHI: {
1306 const PHINode* phi = cast<PHINode>(I);
1307
1308 Out << "PHINode* " << iName << " = new PHINode("
1309 << getCppName(phi->getType()) << ", \"";
1310 printEscapedString(phi->getName());
1311 Out << "\", " << bbname << ");";
1312 nl(Out) << iName << "->reserveOperandSpace("
1313 << phi->getNumIncomingValues()
1314 << ");";
1315 nl(Out);
1316 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1317 Out << iName << "->addIncoming("
1318 << opNames[i] << ", " << opNames[i+1] << ");";
1319 nl(Out);
1320 }
1321 break;
1322 }
1323 case Instruction::Trunc:
1324 case Instruction::ZExt:
1325 case Instruction::SExt:
1326 case Instruction::FPTrunc:
1327 case Instruction::FPExt:
1328 case Instruction::FPToUI:
1329 case Instruction::FPToSI:
1330 case Instruction::UIToFP:
1331 case Instruction::SIToFP:
1332 case Instruction::PtrToInt:
1333 case Instruction::IntToPtr:
1334 case Instruction::BitCast: {
1335 const CastInst* cst = cast<CastInst>(I);
1336 Out << "CastInst* " << iName << " = new ";
1337 switch (I->getOpcode()) {
1338 case Instruction::Trunc: Out << "TruncInst"; break;
1339 case Instruction::ZExt: Out << "ZExtInst"; break;
1340 case Instruction::SExt: Out << "SExtInst"; break;
1341 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1342 case Instruction::FPExt: Out << "FPExtInst"; break;
1343 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1344 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1345 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1346 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1347 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1348 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1349 case Instruction::BitCast: Out << "BitCastInst"; break;
1350 default: assert(!"Unreachable"); break;
1351 }
1352 Out << "(" << opNames[0] << ", "
1353 << getCppName(cst->getType()) << ", \"";
1354 printEscapedString(cst->getName());
1355 Out << "\", " << bbname << ");";
1356 break;
1357 }
1358 case Instruction::Call:{
1359 const CallInst* call = cast<CallInst>(I);
1360 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1361 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1362 << getCppName(ila->getFunctionType()) << ", \""
1363 << ila->getAsmString() << "\", \""
1364 << ila->getConstraintString() << "\","
1365 << (ila->hasSideEffects() ? "true" : "false") << ");";
1366 nl(Out);
1367 }
Reid Spencerefbe90e2007-08-02 03:30:26 +00001368 if (call->getNumOperands() > 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369 Out << "std::vector<Value*> " << iName << "_params;";
1370 nl(Out);
1371 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1372 Out << iName << "_params.push_back(" << opNames[i] << ");";
1373 nl(Out);
1374 }
1375 Out << "CallInst* " << iName << " = new CallInst("
Reid Spencerefbe90e2007-08-02 03:30:26 +00001376 << opNames[0] << ", " << iName << "_params.begin(), "
1377 << iName << "_params.end(), \"";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001378 } else if (call->getNumOperands() == 2) {
1379 Out << "CallInst* " << iName << " = new CallInst("
1380 << opNames[0] << ", " << opNames[1] << ", \"";
1381 } else {
1382 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
1383 << ", \"";
1384 }
1385 printEscapedString(call->getName());
1386 Out << "\", " << bbname << ");";
1387 nl(Out) << iName << "->setCallingConv(";
1388 printCallingConv(call->getCallingConv());
1389 Out << ");";
1390 nl(Out) << iName << "->setTailCall("
1391 << (call->isTailCall() ? "true":"false");
1392 Out << ");";
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001393 printParamAttrs(call->getParamAttrs(), iName);
1394 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1395 nl(Out);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001396 break;
1397 }
1398 case Instruction::Select: {
1399 const SelectInst* sel = cast<SelectInst>(I);
1400 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
1401 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1402 printEscapedString(sel->getName());
1403 Out << "\", " << bbname << ");";
1404 break;
1405 }
1406 case Instruction::UserOp1:
1407 /// FALL THROUGH
1408 case Instruction::UserOp2: {
1409 /// FIXME: What should be done here?
1410 break;
1411 }
1412 case Instruction::VAArg: {
1413 const VAArgInst* va = cast<VAArgInst>(I);
1414 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1415 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1416 printEscapedString(va->getName());
1417 Out << "\", " << bbname << ");";
1418 break;
1419 }
1420 case Instruction::ExtractElement: {
1421 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1422 Out << "ExtractElementInst* " << getCppName(eei)
1423 << " = new ExtractElementInst(" << opNames[0]
1424 << ", " << opNames[1] << ", \"";
1425 printEscapedString(eei->getName());
1426 Out << "\", " << bbname << ");";
1427 break;
1428 }
1429 case Instruction::InsertElement: {
1430 const InsertElementInst* iei = cast<InsertElementInst>(I);
1431 Out << "InsertElementInst* " << getCppName(iei)
1432 << " = new InsertElementInst(" << opNames[0]
1433 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1434 printEscapedString(iei->getName());
1435 Out << "\", " << bbname << ");";
1436 break;
1437 }
1438 case Instruction::ShuffleVector: {
1439 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1440 Out << "ShuffleVectorInst* " << getCppName(svi)
1441 << " = new ShuffleVectorInst(" << opNames[0]
1442 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1443 printEscapedString(svi->getName());
1444 Out << "\", " << bbname << ");";
1445 break;
1446 }
1447 }
1448 DefinedValues.insert(I);
1449 nl(Out);
1450 delete [] opNames;
1451}
1452
1453// Print out the types, constants and declarations needed by one function
1454void CppWriter::printFunctionUses(const Function* F) {
1455
1456 nl(Out) << "// Type Definitions"; nl(Out);
1457 if (!is_inline) {
1458 // Print the function's return type
1459 printType(F->getReturnType());
1460
1461 // Print the function's function type
1462 printType(F->getFunctionType());
1463
1464 // Print the types of each of the function's arguments
1465 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1466 AI != AE; ++AI) {
1467 printType(AI->getType());
1468 }
1469 }
1470
1471 // Print type definitions for every type referenced by an instruction and
1472 // make a note of any global values or constants that are referenced
1473 SmallPtrSet<GlobalValue*,64> gvs;
1474 SmallPtrSet<Constant*,64> consts;
1475 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1476 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1477 I != E; ++I) {
1478 // Print the type of the instruction itself
1479 printType(I->getType());
1480
1481 // Print the type of each of the instruction's operands
1482 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1483 Value* operand = I->getOperand(i);
1484 printType(operand->getType());
1485
1486 // If the operand references a GVal or Constant, make a note of it
1487 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1488 gvs.insert(GV);
1489 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1490 if (GVar->hasInitializer())
1491 consts.insert(GVar->getInitializer());
1492 } else if (Constant* C = dyn_cast<Constant>(operand))
1493 consts.insert(C);
1494 }
1495 }
1496 }
1497
1498 // Print the function declarations for any functions encountered
1499 nl(Out) << "// Function Declarations"; nl(Out);
1500 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1501 I != E; ++I) {
1502 if (Function* Fun = dyn_cast<Function>(*I)) {
1503 if (!is_inline || Fun != F)
1504 printFunctionHead(Fun);
1505 }
1506 }
1507
1508 // Print the global variable declarations for any variables encountered
1509 nl(Out) << "// Global Variable Declarations"; nl(Out);
1510 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1511 I != E; ++I) {
1512 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1513 printVariableHead(F);
1514 }
1515
1516 // Print the constants found
1517 nl(Out) << "// Constant Definitions"; nl(Out);
1518 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(), E = consts.end();
1519 I != E; ++I) {
1520 printConstant(*I);
1521 }
1522
1523 // Process the global variables definitions now that all the constants have
1524 // been emitted. These definitions just couple the gvars with their constant
1525 // initializers.
1526 nl(Out) << "// Global Variable Definitions"; nl(Out);
1527 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1528 I != E; ++I) {
1529 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1530 printVariableBody(GV);
1531 }
1532}
1533
1534void CppWriter::printFunctionHead(const Function* F) {
1535 nl(Out) << "Function* " << getCppName(F);
1536 if (is_inline) {
1537 Out << " = mod->getFunction(\"";
1538 printEscapedString(F->getName());
1539 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1540 nl(Out) << "if (!" << getCppName(F) << ") {";
1541 nl(Out) << getCppName(F);
1542 }
1543 Out<< " = new Function(";
1544 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1545 nl(Out) << "/*Linkage=*/";
1546 printLinkageType(F->getLinkage());
1547 Out << ",";
1548 nl(Out) << "/*Name=*/\"";
1549 printEscapedString(F->getName());
1550 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1551 nl(Out,-1);
1552 printCppName(F);
1553 Out << "->setCallingConv(";
1554 printCallingConv(F->getCallingConv());
1555 Out << ");";
1556 nl(Out);
1557 if (F->hasSection()) {
1558 printCppName(F);
1559 Out << "->setSection(\"" << F->getSection() << "\");";
1560 nl(Out);
1561 }
1562 if (F->getAlignment()) {
1563 printCppName(F);
1564 Out << "->setAlignment(" << F->getAlignment() << ");";
1565 nl(Out);
1566 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001567 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1568 printCppName(F);
1569 Out << "->setVisibility(";
1570 printVisibilityType(F->getVisibility());
1571 Out << ");";
1572 nl(Out);
1573 }
Gordon Henriksen3e7ea1e2007-12-25 22:16:06 +00001574 if (F->hasCollector()) {
1575 printCppName(F);
1576 Out << "->setCollector(\"" << F->getCollector() << "\");";
1577 nl(Out);
1578 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001579 if (is_inline) {
1580 Out << "}";
1581 nl(Out);
1582 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001583 printParamAttrs(F->getParamAttrs(), getCppName(F));
1584 printCppName(F);
1585 Out << "->setParamAttrs(" << getCppName(F) << "_PAL);";
1586 nl(Out);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001587}
1588
1589void CppWriter::printFunctionBody(const Function *F) {
1590 if (F->isDeclaration())
1591 return; // external functions have no bodies.
1592
1593 // Clear the DefinedValues and ForwardRefs maps because we can't have
1594 // cross-function forward refs
1595 ForwardRefs.clear();
1596 DefinedValues.clear();
1597
1598 // Create all the argument values
1599 if (!is_inline) {
1600 if (!F->arg_empty()) {
1601 Out << "Function::arg_iterator args = " << getCppName(F)
1602 << "->arg_begin();";
1603 nl(Out);
1604 }
1605 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1606 AI != AE; ++AI) {
1607 Out << "Value* " << getCppName(AI) << " = args++;";
1608 nl(Out);
1609 if (AI->hasName()) {
1610 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1611 nl(Out);
1612 }
1613 }
1614 }
1615
1616 // Create all the basic blocks
1617 nl(Out);
1618 for (Function::const_iterator BI = F->begin(), BE = F->end();
1619 BI != BE; ++BI) {
1620 std::string bbname(getCppName(BI));
1621 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
1622 if (BI->hasName())
1623 printEscapedString(BI->getName());
1624 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1625 nl(Out);
1626 }
1627
1628 // Output all of its basic blocks... for the function
1629 for (Function::const_iterator BI = F->begin(), BE = F->end();
1630 BI != BE; ++BI) {
1631 std::string bbname(getCppName(BI));
1632 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1633 nl(Out);
1634
1635 // Output all of the instructions in the basic block...
1636 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1637 I != E; ++I) {
1638 printInstruction(I,bbname);
1639 }
1640 }
1641
1642 // Loop over the ForwardRefs and resolve them now that all instructions
1643 // are generated.
1644 if (!ForwardRefs.empty()) {
1645 nl(Out) << "// Resolve Forward References";
1646 nl(Out);
1647 }
1648
1649 while (!ForwardRefs.empty()) {
1650 ForwardRefMap::iterator I = ForwardRefs.begin();
1651 Out << I->second << "->replaceAllUsesWith("
1652 << getCppName(I->first) << "); delete " << I->second << ";";
1653 nl(Out);
1654 ForwardRefs.erase(I);
1655 }
1656}
1657
1658void CppWriter::printInline(const std::string& fname, const std::string& func) {
1659 const Function* F = TheModule->getFunction(func);
1660 if (!F) {
1661 error(std::string("Function '") + func + "' not found in input module");
1662 return;
1663 }
1664 if (F->isDeclaration()) {
1665 error(std::string("Function '") + func + "' is external!");
1666 return;
1667 }
1668 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1669 << getCppName(F);
1670 unsigned arg_count = 1;
1671 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1672 AI != AE; ++AI) {
1673 Out << ", Value* arg_" << arg_count;
1674 }
1675 Out << ") {";
1676 nl(Out);
1677 is_inline = true;
1678 printFunctionUses(F);
1679 printFunctionBody(F);
1680 is_inline = false;
1681 Out << "return " << getCppName(F->begin()) << ";";
1682 nl(Out) << "}";
1683 nl(Out);
1684}
1685
1686void CppWriter::printModuleBody() {
1687 // Print out all the type definitions
1688 nl(Out) << "// Type Definitions"; nl(Out);
1689 printTypes(TheModule);
1690
1691 // Functions can call each other and global variables can reference them so
1692 // define all the functions first before emitting their function bodies.
1693 nl(Out) << "// Function Declarations"; nl(Out);
1694 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1695 I != E; ++I)
1696 printFunctionHead(I);
1697
1698 // Process the global variables declarations. We can't initialze them until
1699 // after the constants are printed so just print a header for each global
1700 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1701 for (Module::const_global_iterator I = TheModule->global_begin(),
1702 E = TheModule->global_end(); I != E; ++I) {
1703 printVariableHead(I);
1704 }
1705
1706 // Print out all the constants definitions. Constants don't recurse except
1707 // through GlobalValues. All GlobalValues have been declared at this point
1708 // so we can proceed to generate the constants.
1709 nl(Out) << "// Constant Definitions"; nl(Out);
1710 printConstants(TheModule);
1711
1712 // Process the global variables definitions now that all the constants have
1713 // been emitted. These definitions just couple the gvars with their constant
1714 // initializers.
1715 nl(Out) << "// Global Variable Definitions"; nl(Out);
1716 for (Module::const_global_iterator I = TheModule->global_begin(),
1717 E = TheModule->global_end(); I != E; ++I) {
1718 printVariableBody(I);
1719 }
1720
1721 // Finally, we can safely put out all of the function bodies.
1722 nl(Out) << "// Function Definitions"; nl(Out);
1723 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1724 I != E; ++I) {
1725 if (!I->isDeclaration()) {
1726 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1727 << ")";
1728 nl(Out) << "{";
1729 nl(Out,1);
1730 printFunctionBody(I);
1731 nl(Out,-1) << "}";
1732 nl(Out);
1733 }
1734 }
1735}
1736
1737void CppWriter::printProgram(
1738 const std::string& fname,
1739 const std::string& mName
1740) {
1741 Out << "#include <llvm/Module.h>\n";
1742 Out << "#include <llvm/DerivedTypes.h>\n";
1743 Out << "#include <llvm/Constants.h>\n";
1744 Out << "#include <llvm/GlobalVariable.h>\n";
1745 Out << "#include <llvm/Function.h>\n";
1746 Out << "#include <llvm/CallingConv.h>\n";
1747 Out << "#include <llvm/BasicBlock.h>\n";
1748 Out << "#include <llvm/Instructions.h>\n";
1749 Out << "#include <llvm/InlineAsm.h>\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001750 Out << "#include <llvm/Support/MathExtras.h>\n";
1751 Out << "#include <llvm/Pass.h>\n";
1752 Out << "#include <llvm/PassManager.h>\n";
1753 Out << "#include <llvm/Analysis/Verifier.h>\n";
1754 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1755 Out << "#include <algorithm>\n";
1756 Out << "#include <iostream>\n\n";
1757 Out << "using namespace llvm;\n\n";
1758 Out << "Module* " << fname << "();\n\n";
1759 Out << "int main(int argc, char**argv) {\n";
1760 Out << " Module* Mod = " << fname << "();\n";
1761 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1762 Out << " std::cerr.flush();\n";
1763 Out << " std::cout.flush();\n";
1764 Out << " PassManager PM;\n";
1765 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1766 Out << " PM.run(*Mod);\n";
1767 Out << " return 0;\n";
1768 Out << "}\n\n";
1769 printModule(fname,mName);
1770}
1771
1772void CppWriter::printModule(
1773 const std::string& fname,
1774 const std::string& mName
1775) {
1776 nl(Out) << "Module* " << fname << "() {";
1777 nl(Out,1) << "// Module Construction";
1778 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1779 if (!TheModule->getTargetTriple().empty()) {
1780 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1781 }
1782 if (!TheModule->getTargetTriple().empty()) {
1783 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1784 << "\");";
1785 }
1786
1787 if (!TheModule->getModuleInlineAsm().empty()) {
1788 nl(Out) << "mod->setModuleInlineAsm(\"";
1789 printEscapedString(TheModule->getModuleInlineAsm());
1790 Out << "\");";
1791 }
1792 nl(Out);
1793
1794 // Loop over the dependent libraries and emit them.
1795 Module::lib_iterator LI = TheModule->lib_begin();
1796 Module::lib_iterator LE = TheModule->lib_end();
1797 while (LI != LE) {
1798 Out << "mod->addLibrary(\"" << *LI << "\");";
1799 nl(Out);
1800 ++LI;
1801 }
1802 printModuleBody();
1803 nl(Out) << "return mod;";
1804 nl(Out,-1) << "}";
1805 nl(Out);
1806}
1807
1808void CppWriter::printContents(
1809 const std::string& fname, // Name of generated function
1810 const std::string& mName // Name of module generated module
1811) {
1812 Out << "\nModule* " << fname << "(Module *mod) {\n";
1813 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1814 printModuleBody();
1815 Out << "\nreturn mod;\n";
1816 Out << "\n}\n";
1817}
1818
1819void CppWriter::printFunction(
1820 const std::string& fname, // Name of generated function
1821 const std::string& funcName // Name of function to generate
1822) {
1823 const Function* F = TheModule->getFunction(funcName);
1824 if (!F) {
1825 error(std::string("Function '") + funcName + "' not found in input module");
1826 return;
1827 }
1828 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1829 printFunctionUses(F);
1830 printFunctionHead(F);
1831 printFunctionBody(F);
1832 Out << "return " << getCppName(F) << ";\n";
1833 Out << "}\n";
1834}
1835
Chris Lattner0366a6d2007-11-13 18:22:33 +00001836void CppWriter::printFunctions() {
1837 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1838 Module::const_iterator I = funcs.begin();
1839 Module::const_iterator IE = funcs.end();
1840
1841 for (; I != IE; ++I) {
1842 const Function &func = *I;
1843 if (!func.isDeclaration()) {
1844 std::string name("define_");
1845 name += func.getName();
1846 printFunction(name, func.getName());
1847 }
1848 }
1849}
1850
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001851void CppWriter::printVariable(
1852 const std::string& fname, /// Name of generated function
1853 const std::string& varName // Name of variable to generate
1854) {
1855 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1856
1857 if (!GV) {
1858 error(std::string("Variable '") + varName + "' not found in input module");
1859 return;
1860 }
1861 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1862 printVariableUses(GV);
1863 printVariableHead(GV);
1864 printVariableBody(GV);
1865 Out << "return " << getCppName(GV) << ";\n";
1866 Out << "}\n";
1867}
1868
1869void CppWriter::printType(
1870 const std::string& fname, /// Name of generated function
1871 const std::string& typeName // Name of type to generate
1872) {
1873 const Type* Ty = TheModule->getTypeByName(typeName);
1874 if (!Ty) {
1875 error(std::string("Type '") + typeName + "' not found in input module");
1876 return;
1877 }
1878 Out << "\nType* " << fname << "(Module *mod) {\n";
1879 printType(Ty);
1880 Out << "return " << getCppName(Ty) << ";\n";
1881 Out << "}\n";
1882}
1883
1884} // end anonymous llvm
1885
1886namespace llvm {
1887
1888void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1889 // Initialize a CppWriter for us to use
1890 CppWriter W(o, mod);
1891
1892 // Emit a header
1893 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1894
1895 // Get the name of the function we're supposed to generate
1896 std::string fname = FuncName.getValue();
1897
1898 // Get the name of the thing we are to generate
1899 std::string tgtname = NameToGenerate.getValue();
1900 if (GenerationType == GenModule ||
1901 GenerationType == GenContents ||
Chris Lattner0366a6d2007-11-13 18:22:33 +00001902 GenerationType == GenProgram ||
1903 GenerationType == GenFunctions) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001904 if (tgtname == "!bad!") {
1905 if (mod->getModuleIdentifier() == "-")
1906 tgtname = "<stdin>";
1907 else
1908 tgtname = mod->getModuleIdentifier();
1909 }
1910 } else if (tgtname == "!bad!") {
1911 W.error("You must use the -for option with -gen-{function,variable,type}");
1912 }
1913
1914 switch (WhatToGenerate(GenerationType)) {
1915 case GenProgram:
1916 if (fname.empty())
1917 fname = "makeLLVMModule";
1918 W.printProgram(fname,tgtname);
1919 break;
1920 case GenModule:
1921 if (fname.empty())
1922 fname = "makeLLVMModule";
1923 W.printModule(fname,tgtname);
1924 break;
1925 case GenContents:
1926 if (fname.empty())
1927 fname = "makeLLVMModuleContents";
1928 W.printContents(fname,tgtname);
1929 break;
1930 case GenFunction:
1931 if (fname.empty())
1932 fname = "makeLLVMFunction";
1933 W.printFunction(fname,tgtname);
1934 break;
Chris Lattner0366a6d2007-11-13 18:22:33 +00001935 case GenFunctions:
1936 W.printFunctions();
1937 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001938 case GenInline:
1939 if (fname.empty())
1940 fname = "makeLLVMInline";
1941 W.printInline(fname,tgtname);
1942 break;
1943 case GenVariable:
1944 if (fname.empty())
1945 fname = "makeLLVMVariable";
1946 W.printVariable(fname,tgtname);
1947 break;
1948 case GenType:
1949 if (fname.empty())
1950 fname = "makeLLVMType";
1951 W.printType(fname,tgtname);
1952 break;
1953 default:
1954 W.error("Invalid generation option");
1955 }
1956}
1957
1958}