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