1 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "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/MC/MCSubtargetInfo.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Target/TargetRegistry.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Config/config.h"
39 static cl::opt<std::string>
40 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
41 cl::value_desc("function name"));
54 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
55 cl::desc("Choose what kind of output to generate"),
58 clEnumValN(GenProgram, "program", "Generate a complete program"),
59 clEnumValN(GenModule, "module", "Generate a module definition"),
60 clEnumValN(GenContents, "contents", "Generate contents of a module"),
61 clEnumValN(GenFunction, "function", "Generate a function definition"),
62 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
63 clEnumValN(GenInline, "inline", "Generate an inline function"),
64 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
65 clEnumValN(GenType, "type", "Generate a type definition"),
70 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
71 cl::desc("Specify the name of the thing to generate"),
74 extern "C" void LLVMInitializeCppBackendTarget() {
75 // Register the target.
76 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
79 extern "C" void LLVMInitializeCppBackendMCSubtargetInfo() {
80 RegisterMCSubtargetInfo<MCSubtargetInfo> X(TheCppBackendTarget);
84 typedef std::vector<const Type*> TypeList;
85 typedef std::map<const Type*,std::string> TypeMap;
86 typedef std::map<const Value*,std::string> ValueMap;
87 typedef std::set<std::string> NameSet;
88 typedef std::set<const Type*> TypeSet;
89 typedef std::set<const Value*> ValueSet;
90 typedef std::map<const Value*,std::string> ForwardRefMap;
92 /// CppWriter - This class is the main chunk of code that converts an LLVM
93 /// module to a C++ translation unit.
94 class CppWriter : public ModulePass {
95 formatted_raw_ostream &Out;
96 const Module *TheModule;
100 TypeMap UnresolvedTypes;
103 TypeSet DefinedTypes;
104 ValueSet DefinedValues;
105 ForwardRefMap ForwardRefs;
107 unsigned indent_level;
111 explicit CppWriter(formatted_raw_ostream &o) :
112 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
114 virtual const char *getPassName() const { return "C++ backend"; }
116 bool runOnModule(Module &M);
118 void printProgram(const std::string& fname, const std::string& modName );
119 void printModule(const std::string& fname, const std::string& modName );
120 void printContents(const std::string& fname, const std::string& modName );
121 void printFunction(const std::string& fname, const std::string& funcName );
122 void printFunctions();
123 void printInline(const std::string& fname, const std::string& funcName );
124 void printVariable(const std::string& fname, const std::string& varName );
125 void printType(const std::string& fname, const std::string& typeName );
127 void error(const std::string& msg);
130 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
131 inline void in() { indent_level++; }
132 inline void out() { if (indent_level >0) indent_level--; }
135 void printLinkageType(GlobalValue::LinkageTypes LT);
136 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
137 void printCallingConv(CallingConv::ID cc);
138 void printEscapedString(const std::string& str);
139 void printCFP(const ConstantFP* CFP);
141 std::string getCppName(const Type* val);
142 inline void printCppName(const Type* val);
144 std::string getCppName(const Value* val);
145 inline void printCppName(const Value* val);
147 void printAttributes(const AttrListPtr &PAL, const std::string &name);
148 bool printTypeInternal(const Type* Ty);
149 inline void printType(const Type* Ty);
150 void printTypes(const Module* M);
152 void printConstant(const Constant *CPV);
153 void printConstants(const Module* M);
155 void printVariableUses(const GlobalVariable *GV);
156 void printVariableHead(const GlobalVariable *GV);
157 void printVariableBody(const GlobalVariable *GV);
159 void printFunctionUses(const Function *F);
160 void printFunctionHead(const Function *F);
161 void printFunctionBody(const Function *F);
162 void printInstruction(const Instruction *I, const std::string& bbname);
163 std::string getOpName(Value*);
165 void printModuleBody();
167 } // end anonymous namespace.
169 formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
171 if (delta >= 0 || indent_level >= unsigned(-delta))
172 indent_level += delta;
173 Out.indent(indent_level);
177 static inline void sanitize(std::string &str) {
178 for (size_t i = 0; i < str.length(); ++i)
179 if (!isalnum(str[i]) && str[i] != '_')
183 static std::string getTypePrefix(const Type *Ty) {
184 switch (Ty->getTypeID()) {
185 case Type::VoidTyID: return "void_";
186 case Type::IntegerTyID:
187 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
188 case Type::FloatTyID: return "float_";
189 case Type::DoubleTyID: return "double_";
190 case Type::LabelTyID: return "label_";
191 case Type::FunctionTyID: return "func_";
192 case Type::StructTyID: return "struct_";
193 case Type::ArrayTyID: return "array_";
194 case Type::PointerTyID: return "ptr_";
195 case Type::VectorTyID: return "packed_";
196 case Type::OpaqueTyID: return "opaque_";
197 default: return "other_";
202 // Looks up the type in the symbol table and returns a pointer to its name or
203 // a null pointer if it wasn't found. Note that this isn't the same as the
204 // Mode::getTypeName function which will return an empty string, not a null
205 // pointer if the name is not found.
206 static const std::string *
207 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
208 TypeSymbolTable::const_iterator TI = ST.begin();
209 TypeSymbolTable::const_iterator TE = ST.end();
210 for (;TI != TE; ++TI)
211 if (TI->second == Ty)
216 void CppWriter::error(const std::string& msg) {
217 report_fatal_error(msg);
220 // printCFP - Print a floating point constant .. very carefully :)
221 // This makes sure that conversion to/from floating yields the same binary
222 // result so that we don't lose precision.
223 void CppWriter::printCFP(const ConstantFP *CFP) {
225 APFloat APF = APFloat(CFP->getValueAPF()); // copy
226 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
227 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
228 Out << "ConstantFP::get(mod->getContext(), ";
232 sprintf(Buffer, "%A", APF.convertToDouble());
233 if ((!strncmp(Buffer, "0x", 2) ||
234 !strncmp(Buffer, "-0x", 3) ||
235 !strncmp(Buffer, "+0x", 3)) &&
236 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
237 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
238 Out << "BitsToDouble(" << Buffer << ")";
240 Out << "BitsToFloat((float)" << Buffer << ")";
244 std::string StrVal = ftostr(CFP->getValueAPF());
246 while (StrVal[0] == ' ')
247 StrVal.erase(StrVal.begin());
249 // Check to make sure that the stringized number is not some string like
250 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
251 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
252 ((StrVal[0] == '-' || StrVal[0] == '+') &&
253 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
254 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
255 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
258 Out << StrVal << "f";
259 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
260 Out << "BitsToDouble(0x"
261 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
262 << "ULL) /* " << StrVal << " */";
264 Out << "BitsToFloat(0x"
265 << utohexstr((uint32_t)CFP->getValueAPF().
266 bitcastToAPInt().getZExtValue())
267 << "U) /* " << StrVal << " */";
275 void CppWriter::printCallingConv(CallingConv::ID cc){
276 // Print the calling convention.
278 case CallingConv::C: Out << "CallingConv::C"; break;
279 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
280 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
281 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
282 default: Out << cc; break;
286 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
288 case GlobalValue::InternalLinkage:
289 Out << "GlobalValue::InternalLinkage"; break;
290 case GlobalValue::PrivateLinkage:
291 Out << "GlobalValue::PrivateLinkage"; break;
292 case GlobalValue::LinkerPrivateLinkage:
293 Out << "GlobalValue::LinkerPrivateLinkage"; break;
294 case GlobalValue::LinkerPrivateWeakLinkage:
295 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
296 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
297 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
298 case GlobalValue::AvailableExternallyLinkage:
299 Out << "GlobalValue::AvailableExternallyLinkage "; break;
300 case GlobalValue::LinkOnceAnyLinkage:
301 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
302 case GlobalValue::LinkOnceODRLinkage:
303 Out << "GlobalValue::LinkOnceODRLinkage "; break;
304 case GlobalValue::WeakAnyLinkage:
305 Out << "GlobalValue::WeakAnyLinkage"; break;
306 case GlobalValue::WeakODRLinkage:
307 Out << "GlobalValue::WeakODRLinkage"; break;
308 case GlobalValue::AppendingLinkage:
309 Out << "GlobalValue::AppendingLinkage"; break;
310 case GlobalValue::ExternalLinkage:
311 Out << "GlobalValue::ExternalLinkage"; break;
312 case GlobalValue::DLLImportLinkage:
313 Out << "GlobalValue::DLLImportLinkage"; break;
314 case GlobalValue::DLLExportLinkage:
315 Out << "GlobalValue::DLLExportLinkage"; break;
316 case GlobalValue::ExternalWeakLinkage:
317 Out << "GlobalValue::ExternalWeakLinkage"; break;
318 case GlobalValue::CommonLinkage:
319 Out << "GlobalValue::CommonLinkage"; break;
323 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
325 default: llvm_unreachable("Unknown GVar visibility");
326 case GlobalValue::DefaultVisibility:
327 Out << "GlobalValue::DefaultVisibility";
329 case GlobalValue::HiddenVisibility:
330 Out << "GlobalValue::HiddenVisibility";
332 case GlobalValue::ProtectedVisibility:
333 Out << "GlobalValue::ProtectedVisibility";
338 // printEscapedString - Print each character of the specified string, escaping
339 // it if it is not printable or if it is an escape char.
340 void CppWriter::printEscapedString(const std::string &Str) {
341 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
342 unsigned char C = Str[i];
343 if (isprint(C) && C != '"' && C != '\\') {
347 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
348 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
353 std::string CppWriter::getCppName(const Type* Ty) {
354 // First, handle the primitive types .. easy
355 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
356 switch (Ty->getTypeID()) {
357 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
358 case Type::IntegerTyID: {
359 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
360 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
362 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
363 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
364 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
365 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
366 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
368 error("Invalid primitive type");
371 // shouldn't be returned, but make it sensible
372 return "Type::getVoidTy(mod->getContext())";
375 // Now, see if we've seen the type before and return that
376 TypeMap::iterator I = TypeNames.find(Ty);
377 if (I != TypeNames.end())
380 // Okay, let's build a new name for this type. Start with a prefix
381 const char* prefix = 0;
382 switch (Ty->getTypeID()) {
383 case Type::FunctionTyID: prefix = "FuncTy_"; break;
384 case Type::StructTyID: prefix = "StructTy_"; break;
385 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
386 case Type::PointerTyID: prefix = "PointerTy_"; break;
387 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
388 case Type::VectorTyID: prefix = "VectorTy_"; break;
389 default: prefix = "OtherTy_"; break; // prevent breakage
392 // See if the type has a name in the symboltable and build accordingly
393 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
396 name = std::string(prefix) + *tName;
398 name = std::string(prefix) + utostr(uniqueNum++);
402 return TypeNames[Ty] = name;
405 void CppWriter::printCppName(const Type* Ty) {
406 printEscapedString(getCppName(Ty));
409 std::string CppWriter::getCppName(const Value* val) {
411 ValueMap::iterator I = ValueNames.find(val);
412 if (I != ValueNames.end() && I->first == val)
415 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
416 name = std::string("gvar_") +
417 getTypePrefix(GV->getType()->getElementType());
418 } else if (isa<Function>(val)) {
419 name = std::string("func_");
420 } else if (const Constant* C = dyn_cast<Constant>(val)) {
421 name = std::string("const_") + getTypePrefix(C->getType());
422 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
424 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
425 Function::const_arg_iterator(Arg)) + 1;
426 name = std::string("arg_") + utostr(argNum);
427 NameSet::iterator NI = UsedNames.find(name);
428 if (NI != UsedNames.end())
429 name += std::string("_") + utostr(uniqueNum++);
430 UsedNames.insert(name);
431 return ValueNames[val] = name;
433 name = getTypePrefix(val->getType());
436 name = getTypePrefix(val->getType());
439 name += val->getName();
441 name += utostr(uniqueNum++);
443 NameSet::iterator NI = UsedNames.find(name);
444 if (NI != UsedNames.end())
445 name += std::string("_") + utostr(uniqueNum++);
446 UsedNames.insert(name);
447 return ValueNames[val] = name;
450 void CppWriter::printCppName(const Value* val) {
451 printEscapedString(getCppName(val));
454 void CppWriter::printAttributes(const AttrListPtr &PAL,
455 const std::string &name) {
456 Out << "AttrListPtr " << name << "_PAL;";
458 if (!PAL.isEmpty()) {
459 Out << '{'; in(); nl(Out);
460 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
461 Out << "AttributeWithIndex PAWI;"; nl(Out);
462 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
463 unsigned index = PAL.getSlot(i).Index;
464 Attributes attrs = PAL.getSlot(i).Attrs;
465 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
466 #define HANDLE_ATTR(X) \
467 if (attrs & Attribute::X) \
468 Out << " | Attribute::" #X; \
469 attrs &= ~Attribute::X;
473 HANDLE_ATTR(NoReturn);
475 HANDLE_ATTR(StructRet);
476 HANDLE_ATTR(NoUnwind);
477 HANDLE_ATTR(NoAlias);
480 HANDLE_ATTR(ReadNone);
481 HANDLE_ATTR(ReadOnly);
482 HANDLE_ATTR(NoInline);
483 HANDLE_ATTR(AlwaysInline);
484 HANDLE_ATTR(OptimizeForSize);
485 HANDLE_ATTR(StackProtect);
486 HANDLE_ATTR(StackProtectReq);
487 HANDLE_ATTR(NoCapture);
488 HANDLE_ATTR(NoRedZone);
489 HANDLE_ATTR(NoImplicitFloat);
491 HANDLE_ATTR(InlineHint);
493 if (attrs & Attribute::StackAlignment)
494 Out << " | Attribute::constructStackAlignmentFromInt("
495 << Attribute::getStackAlignmentFromAttrs(attrs)
497 attrs &= ~Attribute::StackAlignment;
498 assert(attrs == 0 && "Unhandled attribute!");
501 Out << "Attrs.push_back(PAWI);";
504 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
511 bool CppWriter::printTypeInternal(const Type* Ty) {
512 // We don't print definitions for primitive types
513 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
516 // If we already defined this type, we don't need to define it again.
517 if (DefinedTypes.find(Ty) != DefinedTypes.end())
520 // Everything below needs the name for the type so get it now.
521 std::string typeName(getCppName(Ty));
523 // Search the type stack for recursion. If we find it, then generate this
524 // as an OpaqueType, but make sure not to do this multiple times because
525 // the type could appear in multiple places on the stack. Once the opaque
526 // definition is issued, it must not be re-issued. Consequently we have to
527 // check the UnresolvedTypes list as well.
528 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
530 if (TI != TypeStack.end()) {
531 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
532 if (I == UnresolvedTypes.end()) {
533 Out << "PATypeHolder " << typeName;
534 Out << "_fwd = OpaqueType::get(mod->getContext());";
536 UnresolvedTypes[Ty] = typeName;
541 // We're going to print a derived type which, by definition, contains other
542 // types. So, push this one we're printing onto the type stack to assist with
543 // recursive definitions.
544 TypeStack.push_back(Ty);
546 // Print the type definition
547 switch (Ty->getTypeID()) {
548 case Type::FunctionTyID: {
549 const FunctionType* FT = cast<FunctionType>(Ty);
550 Out << "std::vector<const Type*>" << typeName << "_args;";
552 FunctionType::param_iterator PI = FT->param_begin();
553 FunctionType::param_iterator PE = FT->param_end();
554 for (; PI != PE; ++PI) {
555 const Type* argTy = static_cast<const Type*>(*PI);
556 bool isForward = printTypeInternal(argTy);
557 std::string argName(getCppName(argTy));
558 Out << typeName << "_args.push_back(" << argName;
564 bool isForward = printTypeInternal(FT->getReturnType());
565 std::string retTypeName(getCppName(FT->getReturnType()));
566 Out << "FunctionType* " << typeName << " = FunctionType::get(";
567 in(); nl(Out) << "/*Result=*/" << retTypeName;
571 nl(Out) << "/*Params=*/" << typeName << "_args,";
572 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
577 case Type::StructTyID: {
578 const StructType* ST = cast<StructType>(Ty);
579 Out << "std::vector<const Type*>" << typeName << "_fields;";
581 StructType::element_iterator EI = ST->element_begin();
582 StructType::element_iterator EE = ST->element_end();
583 for (; EI != EE; ++EI) {
584 const Type* fieldTy = static_cast<const Type*>(*EI);
585 bool isForward = printTypeInternal(fieldTy);
586 std::string fieldName(getCppName(fieldTy));
587 Out << typeName << "_fields.push_back(" << fieldName;
593 Out << "StructType* " << typeName << " = StructType::get("
594 << typeName << "_fields, /*isPacked=*/"
595 << (ST->isPacked() ? "true" : "false") << ");";
599 case Type::ArrayTyID: {
600 const ArrayType* AT = cast<ArrayType>(Ty);
601 const Type* ET = AT->getElementType();
602 bool isForward = printTypeInternal(ET);
603 std::string elemName(getCppName(ET));
604 Out << "ArrayType* " << typeName << " = ArrayType::get("
605 << elemName << (isForward ? "_fwd" : "")
606 << ", " << utostr(AT->getNumElements()) << ");";
610 case Type::PointerTyID: {
611 const PointerType* PT = cast<PointerType>(Ty);
612 const Type* ET = PT->getElementType();
613 bool isForward = printTypeInternal(ET);
614 std::string elemName(getCppName(ET));
615 Out << "PointerType* " << typeName << " = PointerType::get("
616 << elemName << (isForward ? "_fwd" : "")
617 << ", " << utostr(PT->getAddressSpace()) << ");";
621 case Type::VectorTyID: {
622 const VectorType* PT = cast<VectorType>(Ty);
623 const Type* ET = PT->getElementType();
624 bool isForward = printTypeInternal(ET);
625 std::string elemName(getCppName(ET));
626 Out << "VectorType* " << typeName << " = VectorType::get("
627 << elemName << (isForward ? "_fwd" : "")
628 << ", " << utostr(PT->getNumElements()) << ");";
632 case Type::OpaqueTyID: {
633 Out << "OpaqueType* " << typeName;
634 Out << " = OpaqueType::get(mod->getContext());";
639 error("Invalid TypeID");
642 // If the type had a name, make sure we recreate it.
643 const std::string* progTypeName =
644 findTypeName(TheModule->getTypeSymbolTable(),Ty);
646 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
651 // Pop us off the type stack
652 TypeStack.pop_back();
654 // Indicate that this type is now defined.
655 DefinedTypes.insert(Ty);
657 // Early resolve as many unresolved types as possible. Search the unresolved
658 // types map for the type we just printed. Now that its definition is complete
659 // we can resolve any previous references to it. This prevents a cascade of
661 TypeMap::iterator I = UnresolvedTypes.find(Ty);
662 if (I != UnresolvedTypes.end()) {
663 Out << "cast<OpaqueType>(" << I->second
664 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
666 Out << I->second << " = cast<";
667 switch (Ty->getTypeID()) {
668 case Type::FunctionTyID: Out << "FunctionType"; break;
669 case Type::ArrayTyID: Out << "ArrayType"; break;
670 case Type::StructTyID: Out << "StructType"; break;
671 case Type::VectorTyID: Out << "VectorType"; break;
672 case Type::PointerTyID: Out << "PointerType"; break;
673 case Type::OpaqueTyID: Out << "OpaqueType"; break;
674 default: Out << "NoSuchDerivedType"; break;
676 Out << ">(" << I->second << "_fwd.get());";
678 UnresolvedTypes.erase(I);
681 // Finally, separate the type definition from other with a newline.
684 // We weren't a recursive type
688 // Prints a type definition. Returns true if it could not resolve all the
689 // types in the definition but had to use a forward reference.
690 void CppWriter::printType(const Type* Ty) {
691 assert(TypeStack.empty());
693 printTypeInternal(Ty);
694 assert(TypeStack.empty());
697 void CppWriter::printTypes(const Module* M) {
698 // Walk the symbol table and print out all its types
699 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
700 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
703 // For primitive types and types already defined, just add a name
704 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
705 if (TI->second->isIntegerTy() || TI->second->isPrimitiveType() ||
706 TNI != TypeNames.end()) {
707 Out << "mod->addTypeName(\"";
708 printEscapedString(TI->first);
709 Out << "\", " << getCppName(TI->second) << ");";
711 // For everything else, define the type
713 printType(TI->second);
717 // Add all of the global variables to the value table...
718 for (Module::const_global_iterator I = TheModule->global_begin(),
719 E = TheModule->global_end(); I != E; ++I) {
720 if (I->hasInitializer())
721 printType(I->getInitializer()->getType());
722 printType(I->getType());
725 // Add all the functions to the table
726 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
728 printType(FI->getReturnType());
729 printType(FI->getFunctionType());
730 // Add all the function arguments
731 for (Function::const_arg_iterator AI = FI->arg_begin(),
732 AE = FI->arg_end(); AI != AE; ++AI) {
733 printType(AI->getType());
736 // Add all of the basic blocks and instructions
737 for (Function::const_iterator BB = FI->begin(),
738 E = FI->end(); BB != E; ++BB) {
739 printType(BB->getType());
740 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
742 printType(I->getType());
743 for (unsigned i = 0; i < I->getNumOperands(); ++i)
744 printType(I->getOperand(i)->getType());
751 // printConstant - Print out a constant pool entry...
752 void CppWriter::printConstant(const Constant *CV) {
753 // First, if the constant is actually a GlobalValue (variable or function)
754 // or its already in the constant list then we've printed it already and we
756 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
759 std::string constName(getCppName(CV));
760 std::string typeName(getCppName(CV->getType()));
762 if (isa<GlobalValue>(CV)) {
763 // Skip variables and functions, we emit them elsewhere
767 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
768 std::string constValue = CI->getValue().toString(10, true);
769 Out << "ConstantInt* " << constName
770 << " = ConstantInt::get(mod->getContext(), APInt("
771 << cast<IntegerType>(CI->getType())->getBitWidth()
772 << ", StringRef(\"" << constValue << "\"), 10));";
773 } else if (isa<ConstantAggregateZero>(CV)) {
774 Out << "ConstantAggregateZero* " << constName
775 << " = ConstantAggregateZero::get(" << typeName << ");";
776 } else if (isa<ConstantPointerNull>(CV)) {
777 Out << "ConstantPointerNull* " << constName
778 << " = ConstantPointerNull::get(" << typeName << ");";
779 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
780 Out << "ConstantFP* " << constName << " = ";
783 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
784 if (CA->isString() &&
785 CA->getType()->getElementType() ==
786 Type::getInt8Ty(CA->getContext())) {
787 Out << "Constant* " << constName <<
788 " = ConstantArray::get(mod->getContext(), \"";
789 std::string tmp = CA->getAsString();
790 bool nullTerminate = false;
791 if (tmp[tmp.length()-1] == 0) {
792 tmp.erase(tmp.length()-1);
793 nullTerminate = true;
795 printEscapedString(tmp);
796 // Determine if we want null termination or not.
798 Out << "\", true"; // Indicate that the null terminator should be
801 Out << "\", false";// No null terminator
804 Out << "std::vector<Constant*> " << constName << "_elems;";
806 unsigned N = CA->getNumOperands();
807 for (unsigned i = 0; i < N; ++i) {
808 printConstant(CA->getOperand(i)); // recurse to print operands
809 Out << constName << "_elems.push_back("
810 << getCppName(CA->getOperand(i)) << ");";
813 Out << "Constant* " << constName << " = ConstantArray::get("
814 << typeName << ", " << constName << "_elems);";
816 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
817 Out << "std::vector<Constant*> " << constName << "_fields;";
819 unsigned N = CS->getNumOperands();
820 for (unsigned i = 0; i < N; i++) {
821 printConstant(CS->getOperand(i));
822 Out << constName << "_fields.push_back("
823 << getCppName(CS->getOperand(i)) << ");";
826 Out << "Constant* " << constName << " = ConstantStruct::get("
827 << typeName << ", " << constName << "_fields);";
828 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
829 Out << "std::vector<Constant*> " << constName << "_elems;";
831 unsigned N = CP->getNumOperands();
832 for (unsigned i = 0; i < N; ++i) {
833 printConstant(CP->getOperand(i));
834 Out << constName << "_elems.push_back("
835 << getCppName(CP->getOperand(i)) << ");";
838 Out << "Constant* " << constName << " = ConstantVector::get("
839 << typeName << ", " << constName << "_elems);";
840 } else if (isa<UndefValue>(CV)) {
841 Out << "UndefValue* " << constName << " = UndefValue::get("
843 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
844 if (CE->getOpcode() == Instruction::GetElementPtr) {
845 Out << "std::vector<Constant*> " << constName << "_indices;";
847 printConstant(CE->getOperand(0));
848 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
849 printConstant(CE->getOperand(i));
850 Out << constName << "_indices.push_back("
851 << getCppName(CE->getOperand(i)) << ");";
854 Out << "Constant* " << constName
855 << " = ConstantExpr::getGetElementPtr("
856 << getCppName(CE->getOperand(0)) << ", "
857 << "&" << constName << "_indices[0], "
858 << constName << "_indices.size()"
860 } else if (CE->isCast()) {
861 printConstant(CE->getOperand(0));
862 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
863 switch (CE->getOpcode()) {
864 default: llvm_unreachable("Invalid cast opcode");
865 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
866 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
867 case Instruction::SExt: Out << "Instruction::SExt"; break;
868 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
869 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
870 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
871 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
872 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
873 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
874 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
875 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
876 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
878 Out << ", " << getCppName(CE->getOperand(0)) << ", "
879 << getCppName(CE->getType()) << ");";
881 unsigned N = CE->getNumOperands();
882 for (unsigned i = 0; i < N; ++i ) {
883 printConstant(CE->getOperand(i));
885 Out << "Constant* " << constName << " = ConstantExpr::";
886 switch (CE->getOpcode()) {
887 case Instruction::Add: Out << "getAdd("; break;
888 case Instruction::FAdd: Out << "getFAdd("; break;
889 case Instruction::Sub: Out << "getSub("; break;
890 case Instruction::FSub: Out << "getFSub("; break;
891 case Instruction::Mul: Out << "getMul("; break;
892 case Instruction::FMul: Out << "getFMul("; break;
893 case Instruction::UDiv: Out << "getUDiv("; break;
894 case Instruction::SDiv: Out << "getSDiv("; break;
895 case Instruction::FDiv: Out << "getFDiv("; break;
896 case Instruction::URem: Out << "getURem("; break;
897 case Instruction::SRem: Out << "getSRem("; break;
898 case Instruction::FRem: Out << "getFRem("; break;
899 case Instruction::And: Out << "getAnd("; break;
900 case Instruction::Or: Out << "getOr("; break;
901 case Instruction::Xor: Out << "getXor("; break;
902 case Instruction::ICmp:
903 Out << "getICmp(ICmpInst::ICMP_";
904 switch (CE->getPredicate()) {
905 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
906 case ICmpInst::ICMP_NE: Out << "NE"; break;
907 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
908 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
909 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
910 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
911 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
912 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
913 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
914 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
915 default: error("Invalid ICmp Predicate");
918 case Instruction::FCmp:
919 Out << "getFCmp(FCmpInst::FCMP_";
920 switch (CE->getPredicate()) {
921 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
922 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
923 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
924 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
925 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
926 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
927 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
928 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
929 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
930 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
931 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
932 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
933 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
934 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
935 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
936 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
937 default: error("Invalid FCmp Predicate");
940 case Instruction::Shl: Out << "getShl("; break;
941 case Instruction::LShr: Out << "getLShr("; break;
942 case Instruction::AShr: Out << "getAShr("; break;
943 case Instruction::Select: Out << "getSelect("; break;
944 case Instruction::ExtractElement: Out << "getExtractElement("; break;
945 case Instruction::InsertElement: Out << "getInsertElement("; break;
946 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
948 error("Invalid constant expression");
951 Out << getCppName(CE->getOperand(0));
952 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
953 Out << ", " << getCppName(CE->getOperand(i));
956 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
957 Out << "Constant* " << constName << " = ";
958 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
960 error("Bad Constant");
961 Out << "Constant* " << constName << " = 0; ";
966 void CppWriter::printConstants(const Module* M) {
967 // Traverse all the global variables looking for constant initializers
968 for (Module::const_global_iterator I = TheModule->global_begin(),
969 E = TheModule->global_end(); I != E; ++I)
970 if (I->hasInitializer())
971 printConstant(I->getInitializer());
973 // Traverse the LLVM functions looking for constants
974 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
976 // Add all of the basic blocks and instructions
977 for (Function::const_iterator BB = FI->begin(),
978 E = FI->end(); BB != E; ++BB) {
979 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
981 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
982 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
991 void CppWriter::printVariableUses(const GlobalVariable *GV) {
992 nl(Out) << "// Type Definitions";
994 printType(GV->getType());
995 if (GV->hasInitializer()) {
996 const Constant *Init = GV->getInitializer();
997 printType(Init->getType());
998 if (const Function *F = dyn_cast<Function>(Init)) {
999 nl(Out)<< "/ Function Declarations"; nl(Out);
1000 printFunctionHead(F);
1001 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
1002 nl(Out) << "// Global Variable Declarations"; nl(Out);
1003 printVariableHead(gv);
1005 nl(Out) << "// Global Variable Definitions"; nl(Out);
1006 printVariableBody(gv);
1008 nl(Out) << "// Constant Definitions"; nl(Out);
1009 printConstant(Init);
1014 void CppWriter::printVariableHead(const GlobalVariable *GV) {
1015 nl(Out) << "GlobalVariable* " << getCppName(GV);
1017 Out << " = mod->getGlobalVariable(mod->getContext(), ";
1018 printEscapedString(GV->getName());
1019 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
1020 nl(Out) << "if (!" << getCppName(GV) << ") {";
1021 in(); nl(Out) << getCppName(GV);
1023 Out << " = new GlobalVariable(/*Module=*/*mod, ";
1024 nl(Out) << "/*Type=*/";
1025 printCppName(GV->getType()->getElementType());
1027 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1029 nl(Out) << "/*Linkage=*/";
1030 printLinkageType(GV->getLinkage());
1032 nl(Out) << "/*Initializer=*/0, ";
1033 if (GV->hasInitializer()) {
1034 Out << "// has initializer, specified below";
1036 nl(Out) << "/*Name=*/\"";
1037 printEscapedString(GV->getName());
1041 if (GV->hasSection()) {
1043 Out << "->setSection(\"";
1044 printEscapedString(GV->getSection());
1048 if (GV->getAlignment()) {
1050 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1053 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1055 Out << "->setVisibility(";
1056 printVisibilityType(GV->getVisibility());
1060 if (GV->isThreadLocal()) {
1062 Out << "->setThreadLocal(true);";
1066 out(); Out << "}"; nl(Out);
1070 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1071 if (GV->hasInitializer()) {
1073 Out << "->setInitializer(";
1074 Out << getCppName(GV->getInitializer()) << ");";
1079 std::string CppWriter::getOpName(Value* V) {
1080 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1081 return getCppName(V);
1083 // See if its alread in the map of forward references, if so just return the
1084 // name we already set up for it
1085 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1086 if (I != ForwardRefs.end())
1089 // This is a new forward reference. Generate a unique name for it
1090 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1092 // Yes, this is a hack. An Argument is the smallest instantiable value that
1093 // we can make as a placeholder for the real value. We'll replace these
1094 // Argument instances later.
1095 Out << "Argument* " << result << " = new Argument("
1096 << getCppName(V->getType()) << ");";
1098 ForwardRefs[V] = result;
1102 // printInstruction - This member is called for each Instruction in a function.
1103 void CppWriter::printInstruction(const Instruction *I,
1104 const std::string& bbname) {
1105 std::string iName(getCppName(I));
1107 // Before we emit this instruction, we need to take care of generating any
1108 // forward references. So, we get the names of all the operands in advance
1109 const unsigned Ops(I->getNumOperands());
1110 std::string* opNames = new std::string[Ops];
1111 for (unsigned i = 0; i < Ops; i++)
1112 opNames[i] = getOpName(I->getOperand(i));
1114 switch (I->getOpcode()) {
1116 error("Invalid instruction");
1119 case Instruction::Ret: {
1120 const ReturnInst* ret = cast<ReturnInst>(I);
1121 Out << "ReturnInst::Create(mod->getContext(), "
1122 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1125 case Instruction::Br: {
1126 const BranchInst* br = cast<BranchInst>(I);
1127 Out << "BranchInst::Create(" ;
1128 if (br->getNumOperands() == 3) {
1129 Out << opNames[2] << ", "
1130 << opNames[1] << ", "
1131 << opNames[0] << ", ";
1133 } else if (br->getNumOperands() == 1) {
1134 Out << opNames[0] << ", ";
1136 error("Branch with 2 operands?");
1138 Out << bbname << ");";
1141 case Instruction::Switch: {
1142 const SwitchInst *SI = cast<SwitchInst>(I);
1143 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1144 << opNames[0] << ", "
1145 << opNames[1] << ", "
1146 << SI->getNumCases() << ", " << bbname << ");";
1148 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
1149 Out << iName << "->addCase("
1150 << opNames[i] << ", "
1151 << opNames[i+1] << ");";
1156 case Instruction::IndirectBr: {
1157 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1158 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1159 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1161 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1162 Out << iName << "->addDestination(" << opNames[i] << ");";
1167 case Instruction::Invoke: {
1168 const InvokeInst* inv = cast<InvokeInst>(I);
1169 Out << "std::vector<Value*> " << iName << "_params;";
1171 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1172 Out << iName << "_params.push_back("
1173 << getOpName(inv->getArgOperand(i)) << ");";
1176 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1177 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1178 << getOpName(inv->getCalledFunction()) << ", "
1179 << getOpName(inv->getNormalDest()) << ", "
1180 << getOpName(inv->getUnwindDest()) << ", "
1181 << iName << "_params.begin(), "
1182 << iName << "_params.end(), \"";
1183 printEscapedString(inv->getName());
1184 Out << "\", " << bbname << ");";
1185 nl(Out) << iName << "->setCallingConv(";
1186 printCallingConv(inv->getCallingConv());
1188 printAttributes(inv->getAttributes(), iName);
1189 Out << iName << "->setAttributes(" << iName << "_PAL);";
1193 case Instruction::Unwind: {
1194 Out << "new UnwindInst("
1198 case Instruction::Unreachable: {
1199 Out << "new UnreachableInst("
1200 << "mod->getContext(), "
1204 case Instruction::Add:
1205 case Instruction::FAdd:
1206 case Instruction::Sub:
1207 case Instruction::FSub:
1208 case Instruction::Mul:
1209 case Instruction::FMul:
1210 case Instruction::UDiv:
1211 case Instruction::SDiv:
1212 case Instruction::FDiv:
1213 case Instruction::URem:
1214 case Instruction::SRem:
1215 case Instruction::FRem:
1216 case Instruction::And:
1217 case Instruction::Or:
1218 case Instruction::Xor:
1219 case Instruction::Shl:
1220 case Instruction::LShr:
1221 case Instruction::AShr:{
1222 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1223 switch (I->getOpcode()) {
1224 case Instruction::Add: Out << "Instruction::Add"; break;
1225 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1226 case Instruction::Sub: Out << "Instruction::Sub"; break;
1227 case Instruction::FSub: Out << "Instruction::FSub"; break;
1228 case Instruction::Mul: Out << "Instruction::Mul"; break;
1229 case Instruction::FMul: Out << "Instruction::FMul"; break;
1230 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1231 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1232 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1233 case Instruction::URem:Out << "Instruction::URem"; break;
1234 case Instruction::SRem:Out << "Instruction::SRem"; break;
1235 case Instruction::FRem:Out << "Instruction::FRem"; break;
1236 case Instruction::And: Out << "Instruction::And"; break;
1237 case Instruction::Or: Out << "Instruction::Or"; break;
1238 case Instruction::Xor: Out << "Instruction::Xor"; break;
1239 case Instruction::Shl: Out << "Instruction::Shl"; break;
1240 case Instruction::LShr:Out << "Instruction::LShr"; break;
1241 case Instruction::AShr:Out << "Instruction::AShr"; break;
1242 default: Out << "Instruction::BadOpCode"; break;
1244 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1245 printEscapedString(I->getName());
1246 Out << "\", " << bbname << ");";
1249 case Instruction::FCmp: {
1250 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1251 switch (cast<FCmpInst>(I)->getPredicate()) {
1252 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1253 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1254 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1255 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1256 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1257 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1258 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1259 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1260 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1261 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1262 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1263 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1264 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1265 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1266 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1267 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1268 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1270 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1271 printEscapedString(I->getName());
1275 case Instruction::ICmp: {
1276 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1277 switch (cast<ICmpInst>(I)->getPredicate()) {
1278 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1279 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1280 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1281 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1282 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1283 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1284 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1285 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1286 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1287 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1288 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1290 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1291 printEscapedString(I->getName());
1295 case Instruction::Alloca: {
1296 const AllocaInst* allocaI = cast<AllocaInst>(I);
1297 Out << "AllocaInst* " << iName << " = new AllocaInst("
1298 << getCppName(allocaI->getAllocatedType()) << ", ";
1299 if (allocaI->isArrayAllocation())
1300 Out << opNames[0] << ", ";
1302 printEscapedString(allocaI->getName());
1303 Out << "\", " << bbname << ");";
1304 if (allocaI->getAlignment())
1305 nl(Out) << iName << "->setAlignment("
1306 << allocaI->getAlignment() << ");";
1309 case Instruction::Load: {
1310 const LoadInst* load = cast<LoadInst>(I);
1311 Out << "LoadInst* " << iName << " = new LoadInst("
1312 << opNames[0] << ", \"";
1313 printEscapedString(load->getName());
1314 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1315 << ", " << bbname << ");";
1318 case Instruction::Store: {
1319 const StoreInst* store = cast<StoreInst>(I);
1320 Out << " new StoreInst("
1321 << opNames[0] << ", "
1322 << opNames[1] << ", "
1323 << (store->isVolatile() ? "true" : "false")
1324 << ", " << bbname << ");";
1327 case Instruction::GetElementPtr: {
1328 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1329 if (gep->getNumOperands() <= 2) {
1330 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1332 if (gep->getNumOperands() == 2)
1333 Out << ", " << opNames[1];
1335 Out << "std::vector<Value*> " << iName << "_indices;";
1337 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1338 Out << iName << "_indices.push_back("
1339 << opNames[i] << ");";
1342 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1343 << opNames[0] << ", " << iName << "_indices.begin(), "
1344 << iName << "_indices.end()";
1347 printEscapedString(gep->getName());
1348 Out << "\", " << bbname << ");";
1351 case Instruction::PHI: {
1352 const PHINode* phi = cast<PHINode>(I);
1354 Out << "PHINode* " << iName << " = PHINode::Create("
1355 << getCppName(phi->getType()) << ", "
1356 << phi->getNumIncomingValues() << ", \"";
1357 printEscapedString(phi->getName());
1358 Out << "\", " << bbname << ");";
1360 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
1361 Out << iName << "->addIncoming("
1362 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
1363 << getOpName(phi->getIncomingBlock(i)) << ");";
1368 case Instruction::Trunc:
1369 case Instruction::ZExt:
1370 case Instruction::SExt:
1371 case Instruction::FPTrunc:
1372 case Instruction::FPExt:
1373 case Instruction::FPToUI:
1374 case Instruction::FPToSI:
1375 case Instruction::UIToFP:
1376 case Instruction::SIToFP:
1377 case Instruction::PtrToInt:
1378 case Instruction::IntToPtr:
1379 case Instruction::BitCast: {
1380 const CastInst* cst = cast<CastInst>(I);
1381 Out << "CastInst* " << iName << " = new ";
1382 switch (I->getOpcode()) {
1383 case Instruction::Trunc: Out << "TruncInst"; break;
1384 case Instruction::ZExt: Out << "ZExtInst"; break;
1385 case Instruction::SExt: Out << "SExtInst"; break;
1386 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1387 case Instruction::FPExt: Out << "FPExtInst"; break;
1388 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1389 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1390 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1391 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1392 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1393 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1394 case Instruction::BitCast: Out << "BitCastInst"; break;
1395 default: assert(!"Unreachable"); break;
1397 Out << "(" << opNames[0] << ", "
1398 << getCppName(cst->getType()) << ", \"";
1399 printEscapedString(cst->getName());
1400 Out << "\", " << bbname << ");";
1403 case Instruction::Call: {
1404 const CallInst* call = cast<CallInst>(I);
1405 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1406 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1407 << getCppName(ila->getFunctionType()) << ", \""
1408 << ila->getAsmString() << "\", \""
1409 << ila->getConstraintString() << "\","
1410 << (ila->hasSideEffects() ? "true" : "false") << ");";
1413 if (call->getNumArgOperands() > 1) {
1414 Out << "std::vector<Value*> " << iName << "_params;";
1416 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
1417 Out << iName << "_params.push_back(" << opNames[i] << ");";
1420 Out << "CallInst* " << iName << " = CallInst::Create("
1421 << opNames[call->getNumArgOperands()] << ", "
1422 << iName << "_params.begin(), "
1423 << iName << "_params.end(), \"";
1424 } else if (call->getNumArgOperands() == 1) {
1425 Out << "CallInst* " << iName << " = CallInst::Create("
1426 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
1428 Out << "CallInst* " << iName << " = CallInst::Create("
1429 << opNames[call->getNumArgOperands()] << ", \"";
1431 printEscapedString(call->getName());
1432 Out << "\", " << bbname << ");";
1433 nl(Out) << iName << "->setCallingConv(";
1434 printCallingConv(call->getCallingConv());
1436 nl(Out) << iName << "->setTailCall("
1437 << (call->isTailCall() ? "true" : "false");
1440 printAttributes(call->getAttributes(), iName);
1441 Out << iName << "->setAttributes(" << iName << "_PAL);";
1445 case Instruction::Select: {
1446 const SelectInst* sel = cast<SelectInst>(I);
1447 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1448 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1449 printEscapedString(sel->getName());
1450 Out << "\", " << bbname << ");";
1453 case Instruction::UserOp1:
1455 case Instruction::UserOp2: {
1456 /// FIXME: What should be done here?
1459 case Instruction::VAArg: {
1460 const VAArgInst* va = cast<VAArgInst>(I);
1461 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1462 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1463 printEscapedString(va->getName());
1464 Out << "\", " << bbname << ");";
1467 case Instruction::ExtractElement: {
1468 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1469 Out << "ExtractElementInst* " << getCppName(eei)
1470 << " = new ExtractElementInst(" << opNames[0]
1471 << ", " << opNames[1] << ", \"";
1472 printEscapedString(eei->getName());
1473 Out << "\", " << bbname << ");";
1476 case Instruction::InsertElement: {
1477 const InsertElementInst* iei = cast<InsertElementInst>(I);
1478 Out << "InsertElementInst* " << getCppName(iei)
1479 << " = InsertElementInst::Create(" << opNames[0]
1480 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1481 printEscapedString(iei->getName());
1482 Out << "\", " << bbname << ");";
1485 case Instruction::ShuffleVector: {
1486 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1487 Out << "ShuffleVectorInst* " << getCppName(svi)
1488 << " = new ShuffleVectorInst(" << opNames[0]
1489 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1490 printEscapedString(svi->getName());
1491 Out << "\", " << bbname << ");";
1494 case Instruction::ExtractValue: {
1495 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1496 Out << "std::vector<unsigned> " << iName << "_indices;";
1498 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1499 Out << iName << "_indices.push_back("
1500 << evi->idx_begin()[i] << ");";
1503 Out << "ExtractValueInst* " << getCppName(evi)
1504 << " = ExtractValueInst::Create(" << opNames[0]
1506 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1507 printEscapedString(evi->getName());
1508 Out << "\", " << bbname << ");";
1511 case Instruction::InsertValue: {
1512 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1513 Out << "std::vector<unsigned> " << iName << "_indices;";
1515 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1516 Out << iName << "_indices.push_back("
1517 << ivi->idx_begin()[i] << ");";
1520 Out << "InsertValueInst* " << getCppName(ivi)
1521 << " = InsertValueInst::Create(" << opNames[0]
1522 << ", " << opNames[1] << ", "
1523 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1524 printEscapedString(ivi->getName());
1525 Out << "\", " << bbname << ");";
1529 DefinedValues.insert(I);
1534 // Print out the types, constants and declarations needed by one function
1535 void CppWriter::printFunctionUses(const Function* F) {
1536 nl(Out) << "// Type Definitions"; nl(Out);
1538 // Print the function's return type
1539 printType(F->getReturnType());
1541 // Print the function's function type
1542 printType(F->getFunctionType());
1544 // Print the types of each of the function's arguments
1545 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1547 printType(AI->getType());
1551 // Print type definitions for every type referenced by an instruction and
1552 // make a note of any global values or constants that are referenced
1553 SmallPtrSet<GlobalValue*,64> gvs;
1554 SmallPtrSet<Constant*,64> consts;
1555 for (Function::const_iterator BB = F->begin(), BE = F->end();
1557 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1559 // Print the type of the instruction itself
1560 printType(I->getType());
1562 // Print the type of each of the instruction's operands
1563 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1564 Value* operand = I->getOperand(i);
1565 printType(operand->getType());
1567 // If the operand references a GVal or Constant, make a note of it
1568 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1570 if (GenerationType != GenFunction)
1571 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1572 if (GVar->hasInitializer())
1573 consts.insert(GVar->getInitializer());
1574 } else if (Constant* C = dyn_cast<Constant>(operand)) {
1576 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1577 // If the operand references a GVal or Constant, make a note of it
1578 Value* operand = C->getOperand(j);
1579 printType(operand->getType());
1580 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1582 if (GenerationType != GenFunction)
1583 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1584 if (GVar->hasInitializer())
1585 consts.insert(GVar->getInitializer());
1593 // Print the function declarations for any functions encountered
1594 nl(Out) << "// Function Declarations"; nl(Out);
1595 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1597 if (Function* Fun = dyn_cast<Function>(*I)) {
1598 if (!is_inline || Fun != F)
1599 printFunctionHead(Fun);
1603 // Print the global variable declarations for any variables encountered
1604 nl(Out) << "// Global Variable Declarations"; nl(Out);
1605 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1607 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1608 printVariableHead(F);
1611 // Print the constants found
1612 nl(Out) << "// Constant Definitions"; nl(Out);
1613 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1614 E = consts.end(); I != E; ++I) {
1618 // Process the global variables definitions now that all the constants have
1619 // been emitted. These definitions just couple the gvars with their constant
1621 if (GenerationType != GenFunction) {
1622 nl(Out) << "// Global Variable Definitions"; nl(Out);
1623 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1625 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1626 printVariableBody(GV);
1631 void CppWriter::printFunctionHead(const Function* F) {
1632 nl(Out) << "Function* " << getCppName(F);
1634 Out << " = mod->getFunction(\"";
1635 printEscapedString(F->getName());
1636 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1637 nl(Out) << "if (!" << getCppName(F) << ") {";
1638 nl(Out) << getCppName(F);
1640 Out<< " = Function::Create(";
1641 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1642 nl(Out) << "/*Linkage=*/";
1643 printLinkageType(F->getLinkage());
1645 nl(Out) << "/*Name=*/\"";
1646 printEscapedString(F->getName());
1647 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1650 Out << "->setCallingConv(";
1651 printCallingConv(F->getCallingConv());
1654 if (F->hasSection()) {
1656 Out << "->setSection(\"" << F->getSection() << "\");";
1659 if (F->getAlignment()) {
1661 Out << "->setAlignment(" << F->getAlignment() << ");";
1664 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1666 Out << "->setVisibility(";
1667 printVisibilityType(F->getVisibility());
1673 Out << "->setGC(\"" << F->getGC() << "\");";
1680 printAttributes(F->getAttributes(), getCppName(F));
1682 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1686 void CppWriter::printFunctionBody(const Function *F) {
1687 if (F->isDeclaration())
1688 return; // external functions have no bodies.
1690 // Clear the DefinedValues and ForwardRefs maps because we can't have
1691 // cross-function forward refs
1692 ForwardRefs.clear();
1693 DefinedValues.clear();
1695 // Create all the argument values
1697 if (!F->arg_empty()) {
1698 Out << "Function::arg_iterator args = " << getCppName(F)
1699 << "->arg_begin();";
1702 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1704 Out << "Value* " << getCppName(AI) << " = args++;";
1706 if (AI->hasName()) {
1707 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1713 // Create all the basic blocks
1715 for (Function::const_iterator BI = F->begin(), BE = F->end();
1717 std::string bbname(getCppName(BI));
1718 Out << "BasicBlock* " << bbname <<
1719 " = BasicBlock::Create(mod->getContext(), \"";
1721 printEscapedString(BI->getName());
1722 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1726 // Output all of its basic blocks... for the function
1727 for (Function::const_iterator BI = F->begin(), BE = F->end();
1729 std::string bbname(getCppName(BI));
1730 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1733 // Output all of the instructions in the basic block...
1734 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1736 printInstruction(I,bbname);
1740 // Loop over the ForwardRefs and resolve them now that all instructions
1742 if (!ForwardRefs.empty()) {
1743 nl(Out) << "// Resolve Forward References";
1747 while (!ForwardRefs.empty()) {
1748 ForwardRefMap::iterator I = ForwardRefs.begin();
1749 Out << I->second << "->replaceAllUsesWith("
1750 << getCppName(I->first) << "); delete " << I->second << ";";
1752 ForwardRefs.erase(I);
1756 void CppWriter::printInline(const std::string& fname,
1757 const std::string& func) {
1758 const Function* F = TheModule->getFunction(func);
1760 error(std::string("Function '") + func + "' not found in input module");
1763 if (F->isDeclaration()) {
1764 error(std::string("Function '") + func + "' is external!");
1767 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1769 unsigned arg_count = 1;
1770 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1772 Out << ", Value* arg_" << arg_count;
1777 printFunctionUses(F);
1778 printFunctionBody(F);
1780 Out << "return " << getCppName(F->begin()) << ";";
1785 void CppWriter::printModuleBody() {
1786 // Print out all the type definitions
1787 nl(Out) << "// Type Definitions"; nl(Out);
1788 printTypes(TheModule);
1790 // Functions can call each other and global variables can reference them so
1791 // define all the functions first before emitting their function bodies.
1792 nl(Out) << "// Function Declarations"; nl(Out);
1793 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1795 printFunctionHead(I);
1797 // Process the global variables declarations. We can't initialze them until
1798 // after the constants are printed so just print a header for each global
1799 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1800 for (Module::const_global_iterator I = TheModule->global_begin(),
1801 E = TheModule->global_end(); I != E; ++I) {
1802 printVariableHead(I);
1805 // Print out all the constants definitions. Constants don't recurse except
1806 // through GlobalValues. All GlobalValues have been declared at this point
1807 // so we can proceed to generate the constants.
1808 nl(Out) << "// Constant Definitions"; nl(Out);
1809 printConstants(TheModule);
1811 // Process the global variables definitions now that all the constants have
1812 // been emitted. These definitions just couple the gvars with their constant
1814 nl(Out) << "// Global Variable Definitions"; nl(Out);
1815 for (Module::const_global_iterator I = TheModule->global_begin(),
1816 E = TheModule->global_end(); I != E; ++I) {
1817 printVariableBody(I);
1820 // Finally, we can safely put out all of the function bodies.
1821 nl(Out) << "// Function Definitions"; nl(Out);
1822 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1824 if (!I->isDeclaration()) {
1825 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1829 printFunctionBody(I);
1836 void CppWriter::printProgram(const std::string& fname,
1837 const std::string& mName) {
1838 Out << "#include <llvm/LLVMContext.h>\n";
1839 Out << "#include <llvm/Module.h>\n";
1840 Out << "#include <llvm/DerivedTypes.h>\n";
1841 Out << "#include <llvm/Constants.h>\n";
1842 Out << "#include <llvm/GlobalVariable.h>\n";
1843 Out << "#include <llvm/Function.h>\n";
1844 Out << "#include <llvm/CallingConv.h>\n";
1845 Out << "#include <llvm/BasicBlock.h>\n";
1846 Out << "#include <llvm/Instructions.h>\n";
1847 Out << "#include <llvm/InlineAsm.h>\n";
1848 Out << "#include <llvm/Support/FormattedStream.h>\n";
1849 Out << "#include <llvm/Support/MathExtras.h>\n";
1850 Out << "#include <llvm/Pass.h>\n";
1851 Out << "#include <llvm/PassManager.h>\n";
1852 Out << "#include <llvm/ADT/SmallVector.h>\n";
1853 Out << "#include <llvm/Analysis/Verifier.h>\n";
1854 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1855 Out << "#include <algorithm>\n";
1856 Out << "using namespace llvm;\n\n";
1857 Out << "Module* " << fname << "();\n\n";
1858 Out << "int main(int argc, char**argv) {\n";
1859 Out << " Module* Mod = " << fname << "();\n";
1860 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1861 Out << " PassManager PM;\n";
1862 Out << " PM.add(createPrintModulePass(&outs()));\n";
1863 Out << " PM.run(*Mod);\n";
1864 Out << " return 0;\n";
1866 printModule(fname,mName);
1869 void CppWriter::printModule(const std::string& fname,
1870 const std::string& mName) {
1871 nl(Out) << "Module* " << fname << "() {";
1872 nl(Out,1) << "// Module Construction";
1873 nl(Out) << "Module* mod = new Module(\"";
1874 printEscapedString(mName);
1875 Out << "\", getGlobalContext());";
1876 if (!TheModule->getTargetTriple().empty()) {
1877 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1879 if (!TheModule->getTargetTriple().empty()) {
1880 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1884 if (!TheModule->getModuleInlineAsm().empty()) {
1885 nl(Out) << "mod->setModuleInlineAsm(\"";
1886 printEscapedString(TheModule->getModuleInlineAsm());
1891 // Loop over the dependent libraries and emit them.
1892 Module::lib_iterator LI = TheModule->lib_begin();
1893 Module::lib_iterator LE = TheModule->lib_end();
1895 Out << "mod->addLibrary(\"" << *LI << "\");";
1900 nl(Out) << "return mod;";
1905 void CppWriter::printContents(const std::string& fname,
1906 const std::string& mName) {
1907 Out << "\nModule* " << fname << "(Module *mod) {\n";
1908 Out << "\nmod->setModuleIdentifier(\"";
1909 printEscapedString(mName);
1912 Out << "\nreturn mod;\n";
1916 void CppWriter::printFunction(const std::string& fname,
1917 const std::string& funcName) {
1918 const Function* F = TheModule->getFunction(funcName);
1920 error(std::string("Function '") + funcName + "' not found in input module");
1923 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1924 printFunctionUses(F);
1925 printFunctionHead(F);
1926 printFunctionBody(F);
1927 Out << "return " << getCppName(F) << ";\n";
1931 void CppWriter::printFunctions() {
1932 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1933 Module::const_iterator I = funcs.begin();
1934 Module::const_iterator IE = funcs.end();
1936 for (; I != IE; ++I) {
1937 const Function &func = *I;
1938 if (!func.isDeclaration()) {
1939 std::string name("define_");
1940 name += func.getName();
1941 printFunction(name, func.getName());
1946 void CppWriter::printVariable(const std::string& fname,
1947 const std::string& varName) {
1948 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1951 error(std::string("Variable '") + varName + "' not found in input module");
1954 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1955 printVariableUses(GV);
1956 printVariableHead(GV);
1957 printVariableBody(GV);
1958 Out << "return " << getCppName(GV) << ";\n";
1962 void CppWriter::printType(const std::string& fname,
1963 const std::string& typeName) {
1964 const Type* Ty = TheModule->getTypeByName(typeName);
1966 error(std::string("Type '") + typeName + "' not found in input module");
1969 Out << "\nType* " << fname << "(Module *mod) {\n";
1971 Out << "return " << getCppName(Ty) << ";\n";
1975 bool CppWriter::runOnModule(Module &M) {
1979 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1981 // Get the name of the function we're supposed to generate
1982 std::string fname = FuncName.getValue();
1984 // Get the name of the thing we are to generate
1985 std::string tgtname = NameToGenerate.getValue();
1986 if (GenerationType == GenModule ||
1987 GenerationType == GenContents ||
1988 GenerationType == GenProgram ||
1989 GenerationType == GenFunctions) {
1990 if (tgtname == "!bad!") {
1991 if (M.getModuleIdentifier() == "-")
1992 tgtname = "<stdin>";
1994 tgtname = M.getModuleIdentifier();
1996 } else if (tgtname == "!bad!")
1997 error("You must use the -for option with -gen-{function,variable,type}");
1999 switch (WhatToGenerate(GenerationType)) {
2002 fname = "makeLLVMModule";
2003 printProgram(fname,tgtname);
2007 fname = "makeLLVMModule";
2008 printModule(fname,tgtname);
2012 fname = "makeLLVMModuleContents";
2013 printContents(fname,tgtname);
2017 fname = "makeLLVMFunction";
2018 printFunction(fname,tgtname);
2025 fname = "makeLLVMInline";
2026 printInline(fname,tgtname);
2030 fname = "makeLLVMVariable";
2031 printVariable(fname,tgtname);
2035 fname = "makeLLVMType";
2036 printType(fname,tgtname);
2039 error("Invalid generation option");
2045 char CppWriter::ID = 0;
2047 //===----------------------------------------------------------------------===//
2048 // External Interface declaration
2049 //===----------------------------------------------------------------------===//
2051 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2052 formatted_raw_ostream &o,
2053 CodeGenFileType FileType,
2054 CodeGenOpt::Level OptLevel,
2055 bool DisableVerify) {
2056 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
2057 PM.add(new CppWriter(o));