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