1 //===-- CppWriter.cpp - Printing LLVM IR as a C++ Source File -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CallingConv.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/Instruction.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/SymbolTable.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/CommandLine.h"
34 static cl::opt<std::string>
35 ModName("modname", cl::desc("Specify the module name to use"),
36 cl::value_desc("module name"));
38 static cl::opt<std::string>
39 FuncName("funcname", cl::desc("Specify the name of the generated function"),
40 cl::value_desc("function name"));
43 Fragment("fragment", cl::desc("Don't generate a complete program"));
46 typedef std::vector<const Type*> TypeList;
47 typedef std::map<const Type*,std::string> TypeMap;
48 typedef std::map<const Value*,std::string> ValueMap;
49 typedef std::set<std::string> NameSet;
50 typedef std::set<const Type*> TypeSet;
51 typedef std::set<const Value*> ValueSet;
52 typedef std::map<const Value*,std::string> ForwardRefMap;
56 const Module *TheModule;
57 unsigned long uniqueNum;
60 TypeMap UnresolvedTypes;
64 ValueSet DefinedValues;
65 ForwardRefMap ForwardRefs;
68 inline CppWriter(std::ostream &o, const Module *M)
69 : Out(o), TheModule(M), uniqueNum(0), TypeNames(),
70 ValueNames(), UnresolvedTypes(), TypeStack() { }
72 const Module* getModule() { return TheModule; }
78 void printTypes(const Module* M);
79 void printConstants(const Module* M);
80 void printConstant(const Constant *CPV);
81 void printGlobalHead(const GlobalVariable *GV);
82 void printGlobalBody(const GlobalVariable *GV);
83 void printFunctionHead(const Function *F);
84 void printFunctionBody(const Function *F);
85 void printInstruction(const Instruction *I, const std::string& bbname);
86 void printSymbolTable(const SymbolTable &ST);
87 void printLinkageType(GlobalValue::LinkageTypes LT);
88 void printCallingConv(unsigned cc);
90 std::string getCppName(const Type* val);
91 std::string getCppName(const Value* val);
92 inline void printCppName(const Value* val);
93 inline void printCppName(const Type* val);
94 bool isOnStack(const Type*) const;
95 inline void printTypeDef(const Type* Ty);
96 bool printTypeDefInternal(const Type* Ty);
97 void printEscapedString(const std::string& str);
99 std::string getOpName(Value*);
101 void printCFP(const ConstantFP* CFP);
104 // printCFP - Print a floating point constant .. very carefully :)
105 // This makes sure that conversion to/from floating yields the same binary
106 // result so that we don't lose precision.
108 CppWriter::printCFP(const ConstantFP *CFP) {
111 sprintf(Buffer, "%A", CFP->getValue());
112 if ((!strncmp(Buffer, "0x", 2) ||
113 !strncmp(Buffer, "-0x", 3) ||
114 !strncmp(Buffer, "+0x", 3)) &&
115 (atof(Buffer) == CFP->getValue()))
119 std::string StrVal = ftostr(CFP->getValue());
121 while (StrVal[0] == ' ')
122 StrVal.erase(StrVal.begin());
124 // Check to make sure that the stringized number is not some string like "Inf"
125 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
126 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
127 ((StrVal[0] == '-' || StrVal[0] == '+') &&
128 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
129 (atof(StrVal.c_str()) == CFP->getValue()))
131 else if (CFP->getType() == Type::DoubleTy) {
132 Out << "0x" << std::hex << DoubleToBits(CFP->getValue()) << std::dec
133 << "ULL /* " << StrVal << " */";
135 Out << "0x" << std::hex << FloatToBits(CFP->getValue()) << std::dec
136 << "U /* " << StrVal << " */";
145 CppWriter::getOpName(Value* V) {
146 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
147 return getCppName(V);
149 // See if its alread in the map of forward references, if so just return the
150 // name we already set up for it
151 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
152 if (I != ForwardRefs.end())
155 // This is a new forward reference. Generate a unique name for it
156 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
158 // Yes, this is a hack. An Argument is the smallest instantiable value that
159 // we can make as a placeholder for the real value. We'll replace these
160 // Argument instances later.
161 Out << " Argument* " << result << " = new Argument("
162 << getCppName(V->getType()) << ");\n";
163 ForwardRefs[V] = result;
167 // printEscapedString - Print each character of the specified string, escaping
168 // it if it is not printable or if it is an escape char.
170 CppWriter::printEscapedString(const std::string &Str) {
171 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
172 unsigned char C = Str[i];
173 if (isprint(C) && C != '"' && C != '\\') {
177 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
178 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
184 sanitize(std::string& str) {
185 for (size_t i = 0; i < str.length(); ++i)
186 if (!isalnum(str[i]) && str[i] != '_')
191 getTypePrefix(const Type* Ty ) {
193 switch (Ty->getTypeID()) {
194 case Type::VoidTyID: prefix = "void_"; break;
195 case Type::BoolTyID: prefix = "bool_"; break;
196 case Type::UByteTyID: prefix = "ubyte_"; break;
197 case Type::SByteTyID: prefix = "sbyte_"; break;
198 case Type::UShortTyID: prefix = "ushort_"; break;
199 case Type::ShortTyID: prefix = "short_"; break;
200 case Type::UIntTyID: prefix = "uint_"; break;
201 case Type::IntTyID: prefix = "int_"; break;
202 case Type::ULongTyID: prefix = "ulong_"; break;
203 case Type::LongTyID: prefix = "long_"; break;
204 case Type::FloatTyID: prefix = "float_"; break;
205 case Type::DoubleTyID: prefix = "double_"; break;
206 case Type::LabelTyID: prefix = "label_"; break;
207 case Type::FunctionTyID: prefix = "func_"; break;
208 case Type::StructTyID: prefix = "struct_"; break;
209 case Type::ArrayTyID: prefix = "array_"; break;
210 case Type::PointerTyID: prefix = "ptr_"; break;
211 case Type::PackedTyID: prefix = "packed_"; break;
212 case Type::OpaqueTyID: prefix = "opaque_"; break;
213 default: prefix = "other_"; break;
219 CppWriter::getCppName(const Value* val) {
221 ValueMap::iterator I = ValueNames.find(val);
222 if (I != ValueNames.end() && I->first == val)
225 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
226 name = std::string("gvar_") +
227 getTypePrefix(GV->getType()->getElementType());
228 } else if (const Function* F = dyn_cast<Function>(val)) {
229 name = std::string("func_");
230 } else if (const Constant* C = dyn_cast<Constant>(val)) {
231 name = std::string("const_") + getTypePrefix(C->getType());
233 name = getTypePrefix(val->getType());
235 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
237 NameSet::iterator NI = UsedNames.find(name);
238 if (NI != UsedNames.end())
239 name += std::string("_") + utostr(uniqueNum++);
240 UsedNames.insert(name);
241 return ValueNames[val] = name;
245 CppWriter::printCppName(const Value* val) {
246 printEscapedString(getCppName(val));
250 CppWriter::printCppName(const Type* Ty)
252 printEscapedString(getCppName(Ty));
255 // Gets the C++ name for a type. Returns true if we already saw the type,
258 inline const std::string*
259 findTypeName(const SymbolTable& ST, const Type* Ty)
261 SymbolTable::type_const_iterator TI = ST.type_begin();
262 SymbolTable::type_const_iterator TE = ST.type_end();
263 for (;TI != TE; ++TI)
264 if (TI->second == Ty)
270 CppWriter::getCppName(const Type* Ty)
272 // First, handle the primitive types .. easy
273 if (Ty->isPrimitiveType()) {
274 switch (Ty->getTypeID()) {
275 case Type::VoidTyID: return "Type::VoidTy";
276 case Type::BoolTyID: return "Type::BoolTy";
277 case Type::UByteTyID: return "Type::UByteTy";
278 case Type::SByteTyID: return "Type::SByteTy";
279 case Type::UShortTyID: return "Type::UShortTy";
280 case Type::ShortTyID: return "Type::ShortTy";
281 case Type::UIntTyID: return "Type::UIntTy";
282 case Type::IntTyID: return "Type::IntTy";
283 case Type::ULongTyID: return "Type::ULongTy";
284 case Type::LongTyID: return "Type::LongTy";
285 case Type::FloatTyID: return "Type::FloatTy";
286 case Type::DoubleTyID: return "Type::DoubleTy";
287 case Type::LabelTyID: return "Type::LabelTy";
289 assert(!"Can't get here");
292 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
295 // Now, see if we've seen the type before and return that
296 TypeMap::iterator I = TypeNames.find(Ty);
297 if (I != TypeNames.end())
300 // Okay, let's build a new name for this type. Start with a prefix
301 const char* prefix = 0;
302 switch (Ty->getTypeID()) {
303 case Type::FunctionTyID: prefix = "FuncTy_"; break;
304 case Type::StructTyID: prefix = "StructTy_"; break;
305 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
306 case Type::PointerTyID: prefix = "PointerTy_"; break;
307 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
308 case Type::PackedTyID: prefix = "PackedTy_"; break;
309 default: prefix = "OtherTy_"; break; // prevent breakage
312 // See if the type has a name in the symboltable and build accordingly
313 const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
316 name = std::string(prefix) + *tName;
318 name = std::string(prefix) + utostr(uniqueNum++);
322 return TypeNames[Ty] = name;
325 void CppWriter::printFragment() {
326 // Print out all the type definitions
327 Out << "\n// Type Definitions\n";
328 printTypes(TheModule);
330 // Functions can call each other and global variables can reference them so
331 // define all the functions first before emitting their function bodies.
332 Out << "\n// Function Declarations\n";
333 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
335 printFunctionHead(I);
337 // Process the global variables declarations. We can't initialze them until
338 // after the constants are printed so just print a header for each global
339 Out << "\n// Global Variable Declarations\n";
340 for (Module::const_global_iterator I = TheModule->global_begin(),
341 E = TheModule->global_end(); I != E; ++I) {
345 // Print out all the constants definitions. Constants don't recurse except
346 // through GlobalValues. All GlobalValues have been declared at this point
347 // so we can proceed to generate the constants.
348 Out << "\n// Constant Definitions\n";
349 printConstants(TheModule);
351 // Process the global variables definitions now that all the constants have
352 // been emitted. These definitions just couple the gvars with their constant
354 Out << "\n// Global Variable Definitions\n";
355 for (Module::const_global_iterator I = TheModule->global_begin(),
356 E = TheModule->global_end(); I != E; ++I) {
360 // Finally, we can safely put out all of the function bodies.
361 Out << "\n// Function Definitions\n";
362 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
364 if (!I->isExternal()) {
365 Out << "\n// Function: " << I->getName() << " (" << getCppName(I)
367 printFunctionBody(I);
373 void CppWriter::printModule() {
374 Out << "\n// Module Construction\n";
375 Out << "Module* mod = new Module(\"";
376 if (!ModName.empty())
377 printEscapedString(ModName);
378 else if (TheModule->getModuleIdentifier() == "-")
379 printEscapedString("<stdin>");
381 printEscapedString(TheModule->getModuleIdentifier());
383 Out << "mod->setEndianness(";
384 switch (TheModule->getEndianness()) {
385 case Module::LittleEndian: Out << "Module::LittleEndian);\n"; break;
386 case Module::BigEndian: Out << "Module::BigEndian);\n"; break;
387 case Module::AnyEndianness:Out << "Module::AnyEndianness);\n"; break;
389 Out << "mod->setPointerSize(";
390 switch (TheModule->getPointerSize()) {
391 case Module::Pointer32: Out << "Module::Pointer32);\n"; break;
392 case Module::Pointer64: Out << "Module::Pointer64);\n"; break;
393 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);\n"; break;
395 if (!TheModule->getTargetTriple().empty())
396 Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
399 if (!TheModule->getModuleInlineAsm().empty()) {
400 Out << "mod->setModuleInlineAsm(\"";
401 printEscapedString(TheModule->getModuleInlineAsm());
405 // Loop over the dependent libraries and emit them.
406 Module::lib_iterator LI = TheModule->lib_begin();
407 Module::lib_iterator LE = TheModule->lib_end();
409 Out << "mod->addLibrary(\"" << *LI << "\");\n";
416 CppWriter::printCallingConv(unsigned cc){
417 // Print the calling convention.
419 case CallingConv::C: Out << "CallingConv::C"; break;
420 case CallingConv::CSRet: Out << "CallingConv::CSRet"; break;
421 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
422 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
423 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
424 default: Out << cc; break;
429 CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
431 case GlobalValue::InternalLinkage:
432 Out << "GlobalValue::InternalLinkage"; break;
433 case GlobalValue::LinkOnceLinkage:
434 Out << "GlobalValue::LinkOnceLinkage "; break;
435 case GlobalValue::WeakLinkage:
436 Out << "GlobalValue::WeakLinkage"; break;
437 case GlobalValue::AppendingLinkage:
438 Out << "GlobalValue::AppendingLinkage"; break;
439 case GlobalValue::ExternalLinkage:
440 Out << "GlobalValue::ExternalLinkage"; break;
441 case GlobalValue::GhostLinkage:
442 Out << "GlobalValue::GhostLinkage"; break;
446 void CppWriter::printGlobalHead(const GlobalVariable *GV) {
448 Out << "GlobalVariable* ";
450 Out << " = new GlobalVariable(\n";
452 printCppName(GV->getType()->getElementType());
454 Out << " /*isConstant=*/" << (GV->isConstant()?"true":"false")
455 << ",\n /*Linkage=*/";
456 printLinkageType(GV->getLinkage());
457 Out << ",\n /*Initializer=*/0, ";
458 if (GV->hasInitializer()) {
459 Out << "// has initializer, specified below";
461 Out << "\n /*Name=*/\"";
462 printEscapedString(GV->getName());
463 Out << "\",\n mod);\n";
465 if (GV->hasSection()) {
467 Out << "->setSection(\"";
468 printEscapedString(GV->getSection());
471 if (GV->getAlignment()) {
473 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");\n";
478 CppWriter::printGlobalBody(const GlobalVariable *GV) {
479 if (GV->hasInitializer()) {
481 Out << "->setInitializer(";
482 //if (!isa<GlobalValue(GV->getInitializer()))
484 Out << getCppName(GV->getInitializer()) << ");\n";
489 CppWriter::isOnStack(const Type* Ty) const {
490 TypeList::const_iterator TI =
491 std::find(TypeStack.begin(),TypeStack.end(),Ty);
492 return TI != TypeStack.end();
495 // Prints a type definition. Returns true if it could not resolve all the types
496 // in the definition but had to use a forward reference.
498 CppWriter::printTypeDef(const Type* Ty) {
499 assert(TypeStack.empty());
501 printTypeDefInternal(Ty);
502 assert(TypeStack.empty());
506 CppWriter::printTypeDefInternal(const Type* Ty) {
507 // We don't print definitions for primitive types
508 if (Ty->isPrimitiveType())
511 // If we already defined this type, we don't need to define it again.
512 if (DefinedTypes.find(Ty) != DefinedTypes.end())
515 // Everything below needs the name for the type so get it now.
516 std::string typeName(getCppName(Ty));
518 // Search the type stack for recursion. If we find it, then generate this
519 // as an OpaqueType, but make sure not to do this multiple times because
520 // the type could appear in multiple places on the stack. Once the opaque
521 // definition is issued, it must not be re-issued. Consequently we have to
522 // check the UnresolvedTypes list as well.
524 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
525 if (I == UnresolvedTypes.end()) {
526 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();\n";
527 UnresolvedTypes[Ty] = typeName;
532 // We're going to print a derived type which, by definition, contains other
533 // types. So, push this one we're printing onto the type stack to assist with
534 // recursive definitions.
535 TypeStack.push_back(Ty);
537 // Print the type definition
538 switch (Ty->getTypeID()) {
539 case Type::FunctionTyID: {
540 const FunctionType* FT = cast<FunctionType>(Ty);
541 Out << "std::vector<const Type*>" << typeName << "_args;\n";
542 FunctionType::param_iterator PI = FT->param_begin();
543 FunctionType::param_iterator PE = FT->param_end();
544 for (; PI != PE; ++PI) {
545 const Type* argTy = static_cast<const Type*>(*PI);
546 bool isForward = printTypeDefInternal(argTy);
547 std::string argName(getCppName(argTy));
548 Out << typeName << "_args.push_back(" << argName;
553 bool isForward = printTypeDefInternal(FT->getReturnType());
554 std::string retTypeName(getCppName(FT->getReturnType()));
555 Out << "FunctionType* " << typeName << " = FunctionType::get(\n"
556 << " /*Result=*/" << retTypeName;
559 Out << ",\n /*Params=*/" << typeName << "_args,\n /*isVarArg=*/"
560 << (FT->isVarArg() ? "true" : "false") << ");\n";
563 case Type::StructTyID: {
564 const StructType* ST = cast<StructType>(Ty);
565 Out << "std::vector<const Type*>" << typeName << "_fields;\n";
566 StructType::element_iterator EI = ST->element_begin();
567 StructType::element_iterator EE = ST->element_end();
568 for (; EI != EE; ++EI) {
569 const Type* fieldTy = static_cast<const Type*>(*EI);
570 bool isForward = printTypeDefInternal(fieldTy);
571 std::string fieldName(getCppName(fieldTy));
572 Out << typeName << "_fields.push_back(" << fieldName;
577 Out << "StructType* " << typeName << " = StructType::get("
578 << typeName << "_fields);\n";
581 case Type::ArrayTyID: {
582 const ArrayType* AT = cast<ArrayType>(Ty);
583 const Type* ET = AT->getElementType();
584 bool isForward = printTypeDefInternal(ET);
585 std::string elemName(getCppName(ET));
586 Out << "ArrayType* " << typeName << " = ArrayType::get("
587 << elemName << (isForward ? "_fwd" : "")
588 << ", " << utostr(AT->getNumElements()) << ");\n";
591 case Type::PointerTyID: {
592 const PointerType* PT = cast<PointerType>(Ty);
593 const Type* ET = PT->getElementType();
594 bool isForward = printTypeDefInternal(ET);
595 std::string elemName(getCppName(ET));
596 Out << "PointerType* " << typeName << " = PointerType::get("
597 << elemName << (isForward ? "_fwd" : "") << ");\n";
600 case Type::PackedTyID: {
601 const PackedType* PT = cast<PackedType>(Ty);
602 const Type* ET = PT->getElementType();
603 bool isForward = printTypeDefInternal(ET);
604 std::string elemName(getCppName(ET));
605 Out << "PackedType* " << typeName << " = PackedType::get("
606 << elemName << (isForward ? "_fwd" : "")
607 << ", " << utostr(PT->getNumElements()) << ");\n";
610 case Type::OpaqueTyID: {
611 const OpaqueType* OT = cast<OpaqueType>(Ty);
612 Out << "OpaqueType* " << typeName << " = OpaqueType::get();\n";
616 assert(!"Invalid TypeID");
619 // If the type had a name, make sure we recreate it.
620 const std::string* progTypeName =
621 findTypeName(TheModule->getSymbolTable(),Ty);
623 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
624 << typeName << ");\n";
626 // Pop us off the type stack
627 TypeStack.pop_back();
629 // Indicate that this type is now defined.
630 DefinedTypes.insert(Ty);
632 // Early resolve as many unresolved types as possible. Search the unresolved
633 // types map for the type we just printed. Now that its definition is complete
634 // we can resolve any previous references to it. This prevents a cascade of
636 TypeMap::iterator I = UnresolvedTypes.find(Ty);
637 if (I != UnresolvedTypes.end()) {
638 Out << "cast<OpaqueType>(" << I->second
639 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");\n";
640 Out << I->second << " = cast<";
641 switch (Ty->getTypeID()) {
642 case Type::FunctionTyID: Out << "FunctionType"; break;
643 case Type::ArrayTyID: Out << "ArrayType"; break;
644 case Type::StructTyID: Out << "StructType"; break;
645 case Type::PackedTyID: Out << "PackedType"; break;
646 case Type::PointerTyID: Out << "PointerType"; break;
647 case Type::OpaqueTyID: Out << "OpaqueType"; break;
648 default: Out << "NoSuchDerivedType"; break;
650 Out << ">(" << I->second << "_fwd.get());\n\n";
651 UnresolvedTypes.erase(I);
654 // Finally, separate the type definition from other with a newline.
657 // We weren't a recursive type
662 CppWriter::printTypes(const Module* M) {
664 // Walk the symbol table and print out all its types
665 const SymbolTable& symtab = M->getSymbolTable();
666 for (SymbolTable::type_const_iterator TI = symtab.type_begin(),
667 TE = symtab.type_end(); TI != TE; ++TI) {
669 // For primitive types and types already defined, just add a name
670 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
671 if (TI->second->isPrimitiveType() || TNI != TypeNames.end()) {
672 Out << "mod->addTypeName(\"";
673 printEscapedString(TI->first);
674 Out << "\", " << getCppName(TI->second) << ");\n";
675 // For everything else, define the type
677 printTypeDef(TI->second);
681 // Add all of the global variables to the value table...
682 for (Module::const_global_iterator I = TheModule->global_begin(),
683 E = TheModule->global_end(); I != E; ++I) {
684 if (I->hasInitializer())
685 printTypeDef(I->getInitializer()->getType());
686 printTypeDef(I->getType());
689 // Add all the functions to the table
690 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
692 printTypeDef(FI->getReturnType());
693 printTypeDef(FI->getFunctionType());
694 // Add all the function arguments
695 for(Function::const_arg_iterator AI = FI->arg_begin(),
696 AE = FI->arg_end(); AI != AE; ++AI) {
697 printTypeDef(AI->getType());
700 // Add all of the basic blocks and instructions
701 for (Function::const_iterator BB = FI->begin(),
702 E = FI->end(); BB != E; ++BB) {
703 printTypeDef(BB->getType());
704 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
706 printTypeDef(I->getType());
707 for (unsigned i = 0; i < I->getNumOperands(); ++i)
708 printTypeDef(I->getOperand(i)->getType());
715 CppWriter::printConstants(const Module* M) {
716 // Add all of the global variables to the value table...
717 for (Module::const_global_iterator I = TheModule->global_begin(),
718 E = TheModule->global_end(); I != E; ++I)
719 if (I->hasInitializer())
720 printConstant(I->getInitializer());
722 // Traverse the LLVM functions looking for constants
723 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
725 // Add all of the basic blocks and instructions
726 for (Function::const_iterator BB = FI->begin(),
727 E = FI->end(); BB != E; ++BB) {
728 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
730 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
731 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
740 // printConstant - Print out a constant pool entry...
741 void CppWriter::printConstant(const Constant *CV) {
742 // First, if the constant is actually a GlobalValue (variable or function) or
743 // its already in the constant list then we've printed it already and we can
745 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
748 const int IndentSize = 2;
749 static std::string Indent = "\n";
750 std::string constName(getCppName(CV));
751 std::string typeName(getCppName(CV->getType()));
752 if (CV->isNullValue()) {
753 Out << "Constant* " << constName << " = Constant::getNullValue("
754 << typeName << ");\n";
757 if (isa<GlobalValue>(CV)) {
758 // Skip variables and functions, we emit them elsewhere
761 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
762 Out << "ConstantBool* " << constName << " = ConstantBool::get("
763 << (CB == ConstantBool::True ? "true" : "false")
765 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
766 Out << "ConstantSInt* " << constName << " = ConstantSInt::get("
767 << typeName << ", " << CI->getValue() << ");";
768 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
769 Out << "ConstantUInt* " << constName << " = ConstantUInt::get("
770 << typeName << ", " << CI->getValue() << ");";
771 } else if (isa<ConstantAggregateZero>(CV)) {
772 Out << "ConstantAggregateZero* " << constName
773 << " = ConstantAggregateZero::get(" << typeName << ");";
774 } else if (isa<ConstantPointerNull>(CV)) {
775 Out << "ConstantPointerNull* " << constName
776 << " = ConstanPointerNull::get(" << typeName << ");";
777 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
778 Out << "ConstantFP* " << constName << " = ConstantFP::get(" << typeName
781 sprintf(buffer,"%A",CFP->getValue());
782 // We would like to output the FP constant value in exponential notation,
783 // but we cannot do this if doing so will lose precision. Check here to
784 // make sure that we only output it in exponential format if we can parse
785 // the value back and get the same value.
787 std::string StrVal = ftostr(CFP->getValue());
789 // Check to make sure that the stringized number is not some string like
790 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
791 // the string matches the "[-+]?[0-9]" regex.
793 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
794 ((StrVal[0] == '-' || StrVal[0] == '+') &&
795 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
796 (atof(StrVal.c_str()) == CFP->getValue()))
801 // Otherwise we could not reparse it to exactly the same value, so we must
802 // output the string in hexadecimal format!
803 assert(sizeof(double) == sizeof(uint64_t) &&
804 "assuming that double is 64 bits!");
805 Out << "0x" << std::hex << DoubleToBits(CFP->getValue()) << std::dec
806 << "ULL /* " << StrVal << " */";
809 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
810 if (CA->isString() && CA->getType()->getElementType() == Type::SByteTy) {
811 Out << "Constant* " << constName << " = ConstantArray::get(\"";
812 printEscapedString(CA->getAsString());
813 // Determine if we want null termination or not.
814 if (CA->getType()->getNumElements() <= CA->getAsString().length())
815 Out << "\", false";// No null terminator
817 Out << "\", true"; // Indicate that the null terminator should be added.
820 Out << "std::vector<Constant*> " << constName << "_elems;\n";
821 unsigned N = CA->getNumOperands();
822 for (unsigned i = 0; i < N; ++i) {
823 printConstant(CA->getOperand(i)); // recurse to print operands
824 Out << constName << "_elems.push_back("
825 << getCppName(CA->getOperand(i)) << ");\n";
827 Out << "Constant* " << constName << " = ConstantArray::get("
828 << typeName << ", " << constName << "_elems);";
830 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
831 Out << "std::vector<Constant*> " << constName << "_fields;\n";
832 unsigned N = CS->getNumOperands();
833 for (unsigned i = 0; i < N; i++) {
834 printConstant(CS->getOperand(i));
835 Out << constName << "_fields.push_back("
836 << getCppName(CS->getOperand(i)) << ");\n";
838 Out << "Constant* " << constName << " = ConstantStruct::get("
839 << typeName << ", " << constName << "_fields);";
840 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
841 Out << "std::vector<Constant*> " << constName << "_elems;\n";
842 unsigned N = CP->getNumOperands();
843 for (unsigned i = 0; i < N; ++i) {
844 printConstant(CP->getOperand(i));
845 Out << constName << "_elems.push_back("
846 << getCppName(CP->getOperand(i)) << ");\n";
848 Out << "Constant* " << constName << " = ConstantPacked::get("
849 << typeName << ", " << constName << "_elems);";
850 } else if (isa<UndefValue>(CV)) {
851 Out << "UndefValue* " << constName << " = UndefValue::get("
853 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
854 if (CE->getOpcode() == Instruction::GetElementPtr) {
855 Out << "std::vector<Constant*> " << constName << "_indices;\n";
856 printConstant(CE->getOperand(0));
857 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
858 printConstant(CE->getOperand(i));
859 Out << constName << "_indices.push_back("
860 << getCppName(CE->getOperand(i)) << ");\n";
862 Out << "Constant* " << constName
863 << " = ConstantExpr::getGetElementPtr("
864 << getCppName(CE->getOperand(0)) << ", "
865 << constName << "_indices);";
866 } else if (CE->getOpcode() == Instruction::Cast) {
867 printConstant(CE->getOperand(0));
868 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
869 Out << getCppName(CE->getOperand(0)) << ", " << getCppName(CE->getType())
872 unsigned N = CE->getNumOperands();
873 for (unsigned i = 0; i < N; ++i ) {
874 printConstant(CE->getOperand(i));
876 Out << "Constant* " << constName << " = ConstantExpr::";
877 switch (CE->getOpcode()) {
878 case Instruction::Add: Out << "getAdd"; break;
879 case Instruction::Sub: Out << "getSub"; break;
880 case Instruction::Mul: Out << "getMul"; break;
881 case Instruction::Div: Out << "getDiv"; break;
882 case Instruction::Rem: Out << "getRem"; break;
883 case Instruction::And: Out << "getAnd"; break;
884 case Instruction::Or: Out << "getOr"; break;
885 case Instruction::Xor: Out << "getXor"; break;
886 case Instruction::SetEQ: Out << "getSetEQ"; break;
887 case Instruction::SetNE: Out << "getSetNE"; break;
888 case Instruction::SetLE: Out << "getSetLE"; break;
889 case Instruction::SetGE: Out << "getSetGE"; break;
890 case Instruction::SetLT: Out << "getSetLT"; break;
891 case Instruction::SetGT: Out << "getSetGT"; break;
892 case Instruction::Shl: Out << "getShl"; break;
893 case Instruction::Shr: Out << "getShr"; break;
894 case Instruction::Select: Out << "getSelect"; break;
895 case Instruction::ExtractElement: Out << "getExtractElement"; break;
896 case Instruction::InsertElement: Out << "getInsertElement"; break;
897 case Instruction::ShuffleVector: Out << "getShuffleVector"; break;
899 assert(!"Invalid constant expression");
902 Out << getCppName(CE->getOperand(0));
903 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
904 Out << ", " << getCppName(CE->getOperand(i));
908 assert(!"Bad Constant");
909 Out << "Constant* " << constName << " = 0; ";
914 void CppWriter::printFunctionHead(const Function* F) {
915 Out << "\nFunction* " << getCppName(F) << " = new Function(\n"
916 << " /*Type=*/" << getCppName(F->getFunctionType()) << ",\n"
918 printLinkageType(F->getLinkage());
919 Out << ",\n /*Name=*/\"";
920 printEscapedString(F->getName());
922 << (F->isExternal()? "// (external, no body)" : "") << "\n";
924 Out << "->setCallingConv(";
925 printCallingConv(F->getCallingConv());
927 if (F->hasSection()) {
929 Out << "->setSection(\"" << F->getSection() << "\");\n";
931 if (F->getAlignment()) {
933 Out << "->setAlignment(" << F->getAlignment() << ");\n";
937 void CppWriter::printFunctionBody(const Function *F) {
939 return; // external functions have no bodies.
941 // Clear the DefinedValues and ForwardRefs maps because we can't have
942 // cross-function forward refs
944 DefinedValues.clear();
946 // Create all the argument values
947 if (!F->arg_empty()) {
948 Out << " Function::arg_iterator args = " << getCppName(F)
949 << "->arg_begin();\n";
951 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
953 Out << " Value* " << getCppName(AI) << " = args++;\n";
955 Out << " " << getCppName(AI) << "->setName(\"" << AI->getName()
959 // Create all the basic blocks
961 for (Function::const_iterator BI = F->begin(), BE = F->end();
963 std::string bbname(getCppName(BI));
964 Out << " BasicBlock* " << bbname << " = new BasicBlock(\"";
966 printEscapedString(BI->getName());
967 Out << "\"," << getCppName(BI->getParent()) << ",0);\n";
970 // Output all of its basic blocks... for the function
971 for (Function::const_iterator BI = F->begin(), BE = F->end();
973 std::string bbname(getCppName(BI));
974 Out << "\n // Block " << BI->getName() << " (" << bbname << ")\n";
976 // Output all of the instructions in the basic block...
977 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
979 printInstruction(I,bbname);
983 // Loop over the ForwardRefs and resolve them now that all instructions
985 if (!ForwardRefs.empty())
986 Out << "\n // Resolve Forward References\n";
987 while (!ForwardRefs.empty()) {
988 ForwardRefMap::iterator I = ForwardRefs.begin();
989 Out << " " << I->second << "->replaceAllUsesWith("
990 << getCppName(I->first) << "); delete " << I->second << ";\n";
991 ForwardRefs.erase(I);
995 // printInstruction - This member is called for each Instruction in a function.
997 CppWriter::printInstruction(const Instruction *I, const std::string& bbname)
999 std::string iName(getCppName(I));
1001 // Before we emit this instruction, we need to take care of generating any
1002 // forward references. So, we get the names of all the operands in advance
1003 std::string* opNames = new std::string[I->getNumOperands()];
1004 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1005 opNames[i] = getOpName(I->getOperand(i));
1008 switch (I->getOpcode()) {
1009 case Instruction::Ret: {
1010 const ReturnInst* ret = cast<ReturnInst>(I);
1011 Out << " ReturnInst* " << iName << " = new ReturnInst("
1012 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1015 case Instruction::Br: {
1016 const BranchInst* br = cast<BranchInst>(I);
1017 Out << " BranchInst* " << iName << " = new BranchInst(" ;
1018 if (br->getNumOperands() == 3 ) {
1019 Out << opNames[0] << ", "
1020 << opNames[1] << ", "
1021 << opNames[2] << ", ";
1023 } else if (br->getNumOperands() == 1) {
1024 Out << opNames[0] << ", ";
1026 assert(!"branch with 2 operands?");
1028 Out << bbname << ");";
1031 case Instruction::Switch: {
1032 const SwitchInst* sw = cast<SwitchInst>(I);
1033 Out << " SwitchInst* " << iName << " = new SwitchInst("
1034 << opNames[0] << ", "
1035 << opNames[1] << ", "
1036 << sw->getNumCases() << ", " << bbname << ");\n";
1037 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1038 Out << " " << iName << "->addCase("
1039 << opNames[i] << ", "
1040 << opNames[i+1] << ");\n";
1044 case Instruction::Invoke: {
1045 const InvokeInst* inv = cast<InvokeInst>(I);
1046 Out << " std::vector<Value*> " << iName << "_params;\n";
1047 for (unsigned i = 3; i < inv->getNumOperands(); ++i)
1048 Out << " " << iName << "_params.push_back("
1049 << opNames[i] << ");\n";
1050 Out << " InvokeInst* " << iName << " = new InvokeInst("
1051 << opNames[0] << ", "
1052 << opNames[1] << ", "
1053 << opNames[2] << ", "
1054 << iName << "_params, \"";
1055 printEscapedString(inv->getName());
1056 Out << "\", " << bbname << ");\n";
1057 Out << iName << "->setCallingConv(";
1058 printCallingConv(inv->getCallingConv());
1062 case Instruction::Unwind: {
1063 Out << " UnwindInst* " << iName << " = new UnwindInst("
1067 case Instruction::Unreachable:{
1068 Out << " UnreachableInst* " << iName << " = new UnreachableInst("
1072 case Instruction::Add:
1073 case Instruction::Sub:
1074 case Instruction::Mul:
1075 case Instruction::Div:
1076 case Instruction::Rem:
1077 case Instruction::And:
1078 case Instruction::Or:
1079 case Instruction::Xor:
1080 case Instruction::Shl:
1081 case Instruction::Shr:{
1082 Out << " BinaryOperator* " << iName << " = BinaryOperator::create(";
1083 switch (I->getOpcode()) {
1084 case Instruction::Add: Out << "Instruction::Add"; break;
1085 case Instruction::Sub: Out << "Instruction::Sub"; break;
1086 case Instruction::Mul: Out << "Instruction::Mul"; break;
1087 case Instruction::Div: Out << "Instruction::Div"; break;
1088 case Instruction::Rem: Out << "Instruction::Rem"; break;
1089 case Instruction::And: Out << "Instruction::And"; break;
1090 case Instruction::Or: Out << "Instruction::Or"; break;
1091 case Instruction::Xor: Out << "Instruction::Xor"; break;
1092 case Instruction::Shl: Out << "Instruction::Shl"; break;
1093 case Instruction::Shr: Out << "Instruction::Shr"; break;
1094 default: Out << "Instruction::BadOpCode"; break;
1096 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1097 printEscapedString(I->getName());
1098 Out << "\", " << bbname << ");";
1101 case Instruction::SetEQ:
1102 case Instruction::SetNE:
1103 case Instruction::SetLE:
1104 case Instruction::SetGE:
1105 case Instruction::SetLT:
1106 case Instruction::SetGT: {
1107 Out << " SetCondInst* " << iName << " = new SetCondInst(";
1108 switch (I->getOpcode()) {
1109 case Instruction::SetEQ: Out << "Instruction::SetEQ"; break;
1110 case Instruction::SetNE: Out << "Instruction::SetNE"; break;
1111 case Instruction::SetLE: Out << "Instruction::SetLE"; break;
1112 case Instruction::SetGE: Out << "Instruction::SetGE"; break;
1113 case Instruction::SetLT: Out << "Instruction::SetLT"; break;
1114 case Instruction::SetGT: Out << "Instruction::SetGT"; break;
1115 default: Out << "Instruction::BadOpCode"; break;
1117 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1118 printEscapedString(I->getName());
1119 Out << "\", " << bbname << ");";
1122 case Instruction::Malloc: {
1123 const MallocInst* mallocI = cast<MallocInst>(I);
1124 Out << " MallocInst* " << iName << " = new MallocInst("
1125 << getCppName(mallocI->getAllocatedType()) << ", ";
1126 if (mallocI->isArrayAllocation())
1127 Out << opNames[0] << ", " ;
1129 printEscapedString(mallocI->getName());
1130 Out << "\", " << bbname << ");";
1131 if (mallocI->getAlignment())
1132 Out << "\n " << iName << "->setAlignment("
1133 << mallocI->getAlignment() << ");";
1136 case Instruction::Free: {
1137 Out << " FreeInst* " << iName << " = new FreeInst("
1138 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1141 case Instruction::Alloca: {
1142 const AllocaInst* allocaI = cast<AllocaInst>(I);
1143 Out << " AllocaInst* " << iName << " = new AllocaInst("
1144 << getCppName(allocaI->getAllocatedType()) << ", ";
1145 if (allocaI->isArrayAllocation())
1146 Out << opNames[0] << ", ";
1148 printEscapedString(allocaI->getName());
1149 Out << "\", " << bbname << ");";
1150 if (allocaI->getAlignment())
1151 Out << "\n " << iName << "->setAlignment("
1152 << allocaI->getAlignment() << ");";
1155 case Instruction::Load:{
1156 const LoadInst* load = cast<LoadInst>(I);
1157 Out << " LoadInst* " << iName << " = new LoadInst("
1158 << opNames[0] << ", \"";
1159 printEscapedString(load->getName());
1160 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1161 << ", " << bbname << ");\n";
1164 case Instruction::Store: {
1165 const StoreInst* store = cast<StoreInst>(I);
1166 Out << " StoreInst* " << iName << " = new StoreInst("
1167 << opNames[0] << ", "
1168 << opNames[1] << ", "
1169 << (store->isVolatile() ? "true" : "false")
1170 << ", " << bbname << ");\n";
1173 case Instruction::GetElementPtr: {
1174 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1175 if (gep->getNumOperands() <= 2) {
1176 Out << " GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1178 if (gep->getNumOperands() == 2)
1179 Out << ", " << opNames[1];
1181 Out << " std::vector<Value*> " << iName << "_indices;\n";
1182 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1183 Out << " " << iName << "_indices.push_back("
1184 << opNames[i] << ");\n";
1186 Out << " Instruction* " << iName << " = new GetElementPtrInst("
1187 << opNames[0] << ", " << iName << "_indices";
1190 printEscapedString(gep->getName());
1191 Out << "\", " << bbname << ");";
1194 case Instruction::PHI: {
1195 const PHINode* phi = cast<PHINode>(I);
1197 Out << " PHINode* " << iName << " = new PHINode("
1198 << getCppName(phi->getType()) << ", \"";
1199 printEscapedString(phi->getName());
1200 Out << "\", " << bbname << ");\n";
1201 Out << " " << iName << "->reserveOperandSpace("
1202 << phi->getNumIncomingValues()
1204 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1205 Out << " " << iName << "->addIncoming("
1206 << opNames[i] << ", " << opNames[i+1] << ");\n";
1210 case Instruction::Cast: {
1211 const CastInst* cst = cast<CastInst>(I);
1212 Out << " CastInst* " << iName << " = new CastInst("
1213 << opNames[0] << ", "
1214 << getCppName(cst->getType()) << ", \"";
1215 printEscapedString(cst->getName());
1216 Out << "\", " << bbname << ");\n";
1219 case Instruction::Call:{
1220 const CallInst* call = cast<CallInst>(I);
1221 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1222 Out << " InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1223 << getCppName(ila->getFunctionType()) << ", \""
1224 << ila->getAsmString() << "\", \""
1225 << ila->getConstraintString() << "\","
1226 << (ila->hasSideEffects() ? "true" : "false") << ");\n";
1228 if (call->getNumOperands() > 3) {
1229 Out << " std::vector<Value*> " << iName << "_params;\n";
1230 for (unsigned i = 1; i < call->getNumOperands(); ++i)
1231 Out << " " << iName << "_params.push_back(" << opNames[i] << ");\n";
1232 Out << " CallInst* " << iName << " = new CallInst("
1233 << opNames[0] << ", " << iName << "_params, \"";
1234 } else if (call->getNumOperands() == 3) {
1235 Out << " CallInst* " << iName << " = new CallInst("
1236 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1237 } else if (call->getNumOperands() == 2) {
1238 Out << " CallInst* " << iName << " = new CallInst("
1239 << opNames[0] << ", " << opNames[1] << ", \"";
1241 Out << " CallInst* " << iName << " = new CallInst(" << opNames[0]
1244 printEscapedString(call->getName());
1245 Out << "\", " << bbname << ");\n";
1246 Out << " " << iName << "->setCallingConv(";
1247 printCallingConv(call->getCallingConv());
1249 Out << " " << iName << "->setTailCall("
1250 << (call->isTailCall() ? "true":"false");
1254 case Instruction::Select: {
1255 const SelectInst* sel = cast<SelectInst>(I);
1256 Out << " SelectInst* " << getCppName(sel) << " = new SelectInst(";
1257 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1258 printEscapedString(sel->getName());
1259 Out << "\", " << bbname << ");\n";
1262 case Instruction::UserOp1:
1264 case Instruction::UserOp2: {
1265 /// FIXME: What should be done here?
1268 case Instruction::VAArg: {
1269 const VAArgInst* va = cast<VAArgInst>(I);
1270 Out << " VAArgInst* " << getCppName(va) << " = new VAArgInst("
1271 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1272 printEscapedString(va->getName());
1273 Out << "\", " << bbname << ");\n";
1276 case Instruction::ExtractElement: {
1277 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1278 Out << " ExtractElementInst* " << getCppName(eei)
1279 << " = new ExtractElementInst(" << opNames[0]
1280 << ", " << opNames[1] << ", \"";
1281 printEscapedString(eei->getName());
1282 Out << "\", " << bbname << ");\n";
1285 case Instruction::InsertElement: {
1286 const InsertElementInst* iei = cast<InsertElementInst>(I);
1287 Out << " InsertElementInst* " << getCppName(iei)
1288 << " = new InsertElementInst(" << opNames[0]
1289 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1290 printEscapedString(iei->getName());
1291 Out << "\", " << bbname << ");\n";
1294 case Instruction::ShuffleVector: {
1295 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1296 Out << " ShuffleVectorInst* " << getCppName(svi)
1297 << " = new ShuffleVectorInst(" << opNames[0]
1298 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1299 printEscapedString(svi->getName());
1300 Out << "\", " << bbname << ");\n";
1308 } // end anonymous llvm
1312 void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1313 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1314 std::string fname = FuncName.getValue();
1316 fname = "makeLLVMModule";
1318 o << "Module* " << fname << "(Module *mod) {\n";
1319 CppWriter W(o, mod);
1321 o << "return mod;\n";
1324 o << "#include <llvm/Module.h>\n";
1325 o << "#include <llvm/DerivedTypes.h>\n";
1326 o << "#include <llvm/Constants.h>\n";
1327 o << "#include <llvm/GlobalVariable.h>\n";
1328 o << "#include <llvm/Function.h>\n";
1329 o << "#include <llvm/CallingConv.h>\n";
1330 o << "#include <llvm/BasicBlock.h>\n";
1331 o << "#include <llvm/Instructions.h>\n";
1332 o << "#include <llvm/InlineAsm.h>\n";
1333 o << "#include <llvm/Pass.h>\n";
1334 o << "#include <llvm/PassManager.h>\n";
1335 o << "#include <llvm/Analysis/Verifier.h>\n";
1336 o << "#include <llvm/Assembly/PrintModulePass.h>\n";
1337 o << "#include <algorithm>\n";
1338 o << "#include <iostream>\n\n";
1339 o << "using namespace llvm;\n\n";
1340 o << "Module* " << fname << "();\n\n";
1341 o << "int main(int argc, char**argv) {\n";
1342 o << " Module* Mod = makeLLVMModule();\n";
1343 o << " verifyModule(*Mod, PrintMessageAction);\n";
1344 o << " std::cerr.flush();\n";
1345 o << " std::cout.flush();\n";
1346 o << " PassManager PM;\n";
1347 o << " PM.add(new PrintModulePass(&std::cout));\n";
1348 o << " PM.run(*Mod);\n";
1349 o << " return 0;\n";
1351 o << "Module* " << fname << "() {\n";
1352 CppWriter W(o, mod);
1354 o << "return mod;\n";