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/ADT/SmallPtrSet.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Target/TargetRegistry.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/Config/config.h"
38 static cl::opt<std::string>
39 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
40 cl::value_desc("function name"));
53 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
54 cl::desc("Choose what kind of output to generate"),
57 clEnumValN(GenProgram, "program", "Generate a complete program"),
58 clEnumValN(GenModule, "module", "Generate a module definition"),
59 clEnumValN(GenContents, "contents", "Generate contents of a module"),
60 clEnumValN(GenFunction, "function", "Generate a function definition"),
61 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
62 clEnumValN(GenInline, "inline", "Generate an inline function"),
63 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
64 clEnumValN(GenType, "type", "Generate a type definition"),
69 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
70 cl::desc("Specify the name of the thing to generate"),
73 extern "C" void LLVMInitializeCppBackendTarget() {
74 // Register the target.
75 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
79 typedef std::vector<const Type*> TypeList;
80 typedef std::map<const Type*,std::string> TypeMap;
81 typedef std::map<const Value*,std::string> ValueMap;
82 typedef std::set<std::string> NameSet;
83 typedef std::set<const Type*> TypeSet;
84 typedef std::set<const Value*> ValueSet;
85 typedef std::map<const Value*,std::string> ForwardRefMap;
87 /// CppWriter - This class is the main chunk of code that converts an LLVM
88 /// module to a C++ translation unit.
89 class CppWriter : public ModulePass {
90 formatted_raw_ostream &Out;
91 const Module *TheModule;
95 TypeMap UnresolvedTypes;
99 ValueSet DefinedValues;
100 ForwardRefMap ForwardRefs;
102 unsigned indent_level;
106 explicit CppWriter(formatted_raw_ostream &o) :
107 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
109 virtual const char *getPassName() const { return "C++ backend"; }
111 bool runOnModule(Module &M);
113 void printProgram(const std::string& fname, const std::string& modName );
114 void printModule(const std::string& fname, const std::string& modName );
115 void printContents(const std::string& fname, const std::string& modName );
116 void printFunction(const std::string& fname, const std::string& funcName );
117 void printFunctions();
118 void printInline(const std::string& fname, const std::string& funcName );
119 void printVariable(const std::string& fname, const std::string& varName );
120 void printType(const std::string& fname, const std::string& typeName );
122 void error(const std::string& msg);
125 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
126 inline void in() { indent_level++; }
127 inline void out() { if (indent_level >0) indent_level--; }
130 void printLinkageType(GlobalValue::LinkageTypes LT);
131 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
132 void printCallingConv(CallingConv::ID cc);
133 void printEscapedString(const std::string& str);
134 void printCFP(const ConstantFP* CFP);
136 std::string getCppName(const Type* val);
137 inline void printCppName(const Type* val);
139 std::string getCppName(const Value* val);
140 inline void printCppName(const Value* val);
142 void printAttributes(const AttrListPtr &PAL, const std::string &name);
143 bool printTypeInternal(const Type* Ty);
144 inline void printType(const Type* Ty);
145 void printTypes(const Module* M);
147 void printConstant(const Constant *CPV);
148 void printConstants(const Module* M);
150 void printVariableUses(const GlobalVariable *GV);
151 void printVariableHead(const GlobalVariable *GV);
152 void printVariableBody(const GlobalVariable *GV);
154 void printFunctionUses(const Function *F);
155 void printFunctionHead(const Function *F);
156 void printFunctionBody(const Function *F);
157 void printInstruction(const Instruction *I, const std::string& bbname);
158 std::string getOpName(Value*);
160 void printModuleBody();
162 } // end anonymous namespace.
164 formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
166 if (delta >= 0 || indent_level >= unsigned(-delta))
167 indent_level += delta;
168 Out.indent(indent_level);
172 static inline void sanitize(std::string &str) {
173 for (size_t i = 0; i < str.length(); ++i)
174 if (!isalnum(str[i]) && str[i] != '_')
178 static std::string getTypePrefix(const Type *Ty) {
179 switch (Ty->getTypeID()) {
180 case Type::VoidTyID: return "void_";
181 case Type::IntegerTyID:
182 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
183 case Type::FloatTyID: return "float_";
184 case Type::DoubleTyID: return "double_";
185 case Type::LabelTyID: return "label_";
186 case Type::FunctionTyID: return "func_";
187 case Type::StructTyID: return "struct_";
188 case Type::ArrayTyID: return "array_";
189 case Type::PointerTyID: return "ptr_";
190 case Type::VectorTyID: return "packed_";
191 case Type::OpaqueTyID: return "opaque_";
192 default: return "other_";
197 // Looks up the type in the symbol table and returns a pointer to its name or
198 // a null pointer if it wasn't found. Note that this isn't the same as the
199 // Mode::getTypeName function which will return an empty string, not a null
200 // pointer if the name is not found.
201 static const std::string *
202 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
203 TypeSymbolTable::const_iterator TI = ST.begin();
204 TypeSymbolTable::const_iterator TE = ST.end();
205 for (;TI != TE; ++TI)
206 if (TI->second == Ty)
211 void CppWriter::error(const std::string& msg) {
212 report_fatal_error(msg);
215 // printCFP - Print a floating point constant .. very carefully :)
216 // This makes sure that conversion to/from floating yields the same binary
217 // result so that we don't lose precision.
218 void CppWriter::printCFP(const ConstantFP *CFP) {
220 APFloat APF = APFloat(CFP->getValueAPF()); // copy
221 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
222 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
223 Out << "ConstantFP::get(mod->getContext(), ";
227 sprintf(Buffer, "%A", APF.convertToDouble());
228 if ((!strncmp(Buffer, "0x", 2) ||
229 !strncmp(Buffer, "-0x", 3) ||
230 !strncmp(Buffer, "+0x", 3)) &&
231 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
232 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
233 Out << "BitsToDouble(" << Buffer << ")";
235 Out << "BitsToFloat((float)" << Buffer << ")";
239 std::string StrVal = ftostr(CFP->getValueAPF());
241 while (StrVal[0] == ' ')
242 StrVal.erase(StrVal.begin());
244 // Check to make sure that the stringized number is not some string like
245 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
246 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
247 ((StrVal[0] == '-' || StrVal[0] == '+') &&
248 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
249 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
250 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
253 Out << StrVal << "f";
254 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
255 Out << "BitsToDouble(0x"
256 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
257 << "ULL) /* " << StrVal << " */";
259 Out << "BitsToFloat(0x"
260 << utohexstr((uint32_t)CFP->getValueAPF().
261 bitcastToAPInt().getZExtValue())
262 << "U) /* " << StrVal << " */";
270 void CppWriter::printCallingConv(CallingConv::ID cc){
271 // Print the calling convention.
273 case CallingConv::C: Out << "CallingConv::C"; break;
274 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
275 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
276 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
277 default: Out << cc; break;
281 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
283 case GlobalValue::InternalLinkage:
284 Out << "GlobalValue::InternalLinkage"; break;
285 case GlobalValue::PrivateLinkage:
286 Out << "GlobalValue::PrivateLinkage"; break;
287 case GlobalValue::LinkerPrivateLinkage:
288 Out << "GlobalValue::LinkerPrivateLinkage"; break;
289 case GlobalValue::LinkerPrivateWeakLinkage:
290 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
291 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
292 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
293 case GlobalValue::AvailableExternallyLinkage:
294 Out << "GlobalValue::AvailableExternallyLinkage "; break;
295 case GlobalValue::LinkOnceAnyLinkage:
296 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
297 case GlobalValue::LinkOnceODRLinkage:
298 Out << "GlobalValue::LinkOnceODRLinkage "; break;
299 case GlobalValue::WeakAnyLinkage:
300 Out << "GlobalValue::WeakAnyLinkage"; break;
301 case GlobalValue::WeakODRLinkage:
302 Out << "GlobalValue::WeakODRLinkage"; break;
303 case GlobalValue::AppendingLinkage:
304 Out << "GlobalValue::AppendingLinkage"; break;
305 case GlobalValue::ExternalLinkage:
306 Out << "GlobalValue::ExternalLinkage"; break;
307 case GlobalValue::DLLImportLinkage:
308 Out << "GlobalValue::DLLImportLinkage"; break;
309 case GlobalValue::DLLExportLinkage:
310 Out << "GlobalValue::DLLExportLinkage"; break;
311 case GlobalValue::ExternalWeakLinkage:
312 Out << "GlobalValue::ExternalWeakLinkage"; break;
313 case GlobalValue::CommonLinkage:
314 Out << "GlobalValue::CommonLinkage"; break;
318 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
320 default: llvm_unreachable("Unknown GVar visibility");
321 case GlobalValue::DefaultVisibility:
322 Out << "GlobalValue::DefaultVisibility";
324 case GlobalValue::HiddenVisibility:
325 Out << "GlobalValue::HiddenVisibility";
327 case GlobalValue::ProtectedVisibility:
328 Out << "GlobalValue::ProtectedVisibility";
333 // printEscapedString - Print each character of the specified string, escaping
334 // it if it is not printable or if it is an escape char.
335 void CppWriter::printEscapedString(const std::string &Str) {
336 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
337 unsigned char C = Str[i];
338 if (isprint(C) && C != '"' && C != '\\') {
342 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
343 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
348 std::string CppWriter::getCppName(const Type* Ty) {
349 // First, handle the primitive types .. easy
350 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
351 switch (Ty->getTypeID()) {
352 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
353 case Type::IntegerTyID: {
354 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
355 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
357 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
358 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
359 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
360 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
361 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
363 error("Invalid primitive type");
366 // shouldn't be returned, but make it sensible
367 return "Type::getVoidTy(mod->getContext())";
370 // Now, see if we've seen the type before and return that
371 TypeMap::iterator I = TypeNames.find(Ty);
372 if (I != TypeNames.end())
375 // Okay, let's build a new name for this type. Start with a prefix
376 const char* prefix = 0;
377 switch (Ty->getTypeID()) {
378 case Type::FunctionTyID: prefix = "FuncTy_"; break;
379 case Type::StructTyID: prefix = "StructTy_"; break;
380 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
381 case Type::PointerTyID: prefix = "PointerTy_"; break;
382 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
383 case Type::VectorTyID: prefix = "VectorTy_"; break;
384 default: prefix = "OtherTy_"; break; // prevent breakage
387 // See if the type has a name in the symboltable and build accordingly
388 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
391 name = std::string(prefix) + *tName;
393 name = std::string(prefix) + utostr(uniqueNum++);
397 return TypeNames[Ty] = name;
400 void CppWriter::printCppName(const Type* Ty) {
401 printEscapedString(getCppName(Ty));
404 std::string CppWriter::getCppName(const Value* val) {
406 ValueMap::iterator I = ValueNames.find(val);
407 if (I != ValueNames.end() && I->first == val)
410 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
411 name = std::string("gvar_") +
412 getTypePrefix(GV->getType()->getElementType());
413 } else if (isa<Function>(val)) {
414 name = std::string("func_");
415 } else if (const Constant* C = dyn_cast<Constant>(val)) {
416 name = std::string("const_") + getTypePrefix(C->getType());
417 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
419 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
420 Function::const_arg_iterator(Arg)) + 1;
421 name = std::string("arg_") + utostr(argNum);
422 NameSet::iterator NI = UsedNames.find(name);
423 if (NI != UsedNames.end())
424 name += std::string("_") + utostr(uniqueNum++);
425 UsedNames.insert(name);
426 return ValueNames[val] = name;
428 name = getTypePrefix(val->getType());
431 name = getTypePrefix(val->getType());
434 name += val->getName();
436 name += utostr(uniqueNum++);
438 NameSet::iterator NI = UsedNames.find(name);
439 if (NI != UsedNames.end())
440 name += std::string("_") + utostr(uniqueNum++);
441 UsedNames.insert(name);
442 return ValueNames[val] = name;
445 void CppWriter::printCppName(const Value* val) {
446 printEscapedString(getCppName(val));
449 void CppWriter::printAttributes(const AttrListPtr &PAL,
450 const std::string &name) {
451 Out << "AttrListPtr " << name << "_PAL;";
453 if (!PAL.isEmpty()) {
454 Out << '{'; in(); nl(Out);
455 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
456 Out << "AttributeWithIndex PAWI;"; nl(Out);
457 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
458 unsigned index = PAL.getSlot(i).Index;
459 Attributes attrs = PAL.getSlot(i).Attrs;
460 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
461 #define HANDLE_ATTR(X) \
462 if (attrs & Attribute::X) \
463 Out << " | Attribute::" #X; \
464 attrs &= ~Attribute::X;
468 HANDLE_ATTR(NoReturn);
470 HANDLE_ATTR(StructRet);
471 HANDLE_ATTR(NoUnwind);
472 HANDLE_ATTR(NoAlias);
475 HANDLE_ATTR(ReadNone);
476 HANDLE_ATTR(ReadOnly);
477 HANDLE_ATTR(NoInline);
478 HANDLE_ATTR(AlwaysInline);
479 HANDLE_ATTR(OptimizeForSize);
480 HANDLE_ATTR(StackProtect);
481 HANDLE_ATTR(StackProtectReq);
482 HANDLE_ATTR(NoCapture);
483 HANDLE_ATTR(NoRedZone);
484 HANDLE_ATTR(NoImplicitFloat);
486 HANDLE_ATTR(InlineHint);
488 if (attrs & Attribute::StackAlignment)
489 Out << " | Attribute::constructStackAlignmentFromInt("
490 << Attribute::getStackAlignmentFromAttrs(attrs)
492 attrs &= ~Attribute::StackAlignment;
493 assert(attrs == 0 && "Unhandled attribute!");
496 Out << "Attrs.push_back(PAWI);";
499 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
506 bool CppWriter::printTypeInternal(const Type* Ty) {
507 // We don't print definitions for primitive types
508 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
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.
523 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
525 if (TI != TypeStack.end()) {
526 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
527 if (I == UnresolvedTypes.end()) {
528 Out << "PATypeHolder " << typeName;
529 Out << "_fwd = OpaqueType::get(mod->getContext());";
531 UnresolvedTypes[Ty] = typeName;
536 // We're going to print a derived type which, by definition, contains other
537 // types. So, push this one we're printing onto the type stack to assist with
538 // recursive definitions.
539 TypeStack.push_back(Ty);
541 // Print the type definition
542 switch (Ty->getTypeID()) {
543 case Type::FunctionTyID: {
544 const FunctionType* FT = cast<FunctionType>(Ty);
545 Out << "std::vector<const Type*>" << typeName << "_args;";
547 FunctionType::param_iterator PI = FT->param_begin();
548 FunctionType::param_iterator PE = FT->param_end();
549 for (; PI != PE; ++PI) {
550 const Type* argTy = static_cast<const Type*>(*PI);
551 bool isForward = printTypeInternal(argTy);
552 std::string argName(getCppName(argTy));
553 Out << typeName << "_args.push_back(" << argName;
559 bool isForward = printTypeInternal(FT->getReturnType());
560 std::string retTypeName(getCppName(FT->getReturnType()));
561 Out << "FunctionType* " << typeName << " = FunctionType::get(";
562 in(); nl(Out) << "/*Result=*/" << retTypeName;
566 nl(Out) << "/*Params=*/" << typeName << "_args,";
567 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
572 case Type::StructTyID: {
573 const StructType* ST = cast<StructType>(Ty);
574 Out << "std::vector<const Type*>" << typeName << "_fields;";
576 StructType::element_iterator EI = ST->element_begin();
577 StructType::element_iterator EE = ST->element_end();
578 for (; EI != EE; ++EI) {
579 const Type* fieldTy = static_cast<const Type*>(*EI);
580 bool isForward = printTypeInternal(fieldTy);
581 std::string fieldName(getCppName(fieldTy));
582 Out << typeName << "_fields.push_back(" << fieldName;
588 Out << "StructType* " << typeName << " = StructType::get("
589 << "mod->getContext(), "
590 << typeName << "_fields, /*isPacked=*/"
591 << (ST->isPacked() ? "true" : "false") << ");";
595 case Type::ArrayTyID: {
596 const ArrayType* AT = cast<ArrayType>(Ty);
597 const Type* ET = AT->getElementType();
598 bool isForward = printTypeInternal(ET);
599 std::string elemName(getCppName(ET));
600 Out << "ArrayType* " << typeName << " = ArrayType::get("
601 << elemName << (isForward ? "_fwd" : "")
602 << ", " << utostr(AT->getNumElements()) << ");";
606 case Type::PointerTyID: {
607 const PointerType* PT = cast<PointerType>(Ty);
608 const Type* ET = PT->getElementType();
609 bool isForward = printTypeInternal(ET);
610 std::string elemName(getCppName(ET));
611 Out << "PointerType* " << typeName << " = PointerType::get("
612 << elemName << (isForward ? "_fwd" : "")
613 << ", " << utostr(PT->getAddressSpace()) << ");";
617 case Type::VectorTyID: {
618 const VectorType* PT = cast<VectorType>(Ty);
619 const Type* ET = PT->getElementType();
620 bool isForward = printTypeInternal(ET);
621 std::string elemName(getCppName(ET));
622 Out << "VectorType* " << typeName << " = VectorType::get("
623 << elemName << (isForward ? "_fwd" : "")
624 << ", " << utostr(PT->getNumElements()) << ");";
628 case Type::OpaqueTyID: {
629 Out << "OpaqueType* " << typeName;
630 Out << " = OpaqueType::get(mod->getContext());";
635 error("Invalid TypeID");
638 // If the type had a name, make sure we recreate it.
639 const std::string* progTypeName =
640 findTypeName(TheModule->getTypeSymbolTable(),Ty);
642 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
647 // Pop us off the type stack
648 TypeStack.pop_back();
650 // Indicate that this type is now defined.
651 DefinedTypes.insert(Ty);
653 // Early resolve as many unresolved types as possible. Search the unresolved
654 // types map for the type we just printed. Now that its definition is complete
655 // we can resolve any previous references to it. This prevents a cascade of
657 TypeMap::iterator I = UnresolvedTypes.find(Ty);
658 if (I != UnresolvedTypes.end()) {
659 Out << "cast<OpaqueType>(" << I->second
660 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
662 Out << I->second << " = cast<";
663 switch (Ty->getTypeID()) {
664 case Type::FunctionTyID: Out << "FunctionType"; break;
665 case Type::ArrayTyID: Out << "ArrayType"; break;
666 case Type::StructTyID: Out << "StructType"; break;
667 case Type::VectorTyID: Out << "VectorType"; break;
668 case Type::PointerTyID: Out << "PointerType"; break;
669 case Type::OpaqueTyID: Out << "OpaqueType"; break;
670 default: Out << "NoSuchDerivedType"; break;
672 Out << ">(" << I->second << "_fwd.get());";
674 UnresolvedTypes.erase(I);
677 // Finally, separate the type definition from other with a newline.
680 // We weren't a recursive type
684 // Prints a type definition. Returns true if it could not resolve all the
685 // types in the definition but had to use a forward reference.
686 void CppWriter::printType(const Type* Ty) {
687 assert(TypeStack.empty());
689 printTypeInternal(Ty);
690 assert(TypeStack.empty());
693 void CppWriter::printTypes(const Module* M) {
694 // Walk the symbol table and print out all its types
695 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
696 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
699 // For primitive types and types already defined, just add a name
700 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
701 if (TI->second->isIntegerTy() || TI->second->isPrimitiveType() ||
702 TNI != TypeNames.end()) {
703 Out << "mod->addTypeName(\"";
704 printEscapedString(TI->first);
705 Out << "\", " << getCppName(TI->second) << ");";
707 // For everything else, define the type
709 printType(TI->second);
713 // Add all of the global variables to the value table...
714 for (Module::const_global_iterator I = TheModule->global_begin(),
715 E = TheModule->global_end(); I != E; ++I) {
716 if (I->hasInitializer())
717 printType(I->getInitializer()->getType());
718 printType(I->getType());
721 // Add all the functions to the table
722 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
724 printType(FI->getReturnType());
725 printType(FI->getFunctionType());
726 // Add all the function arguments
727 for (Function::const_arg_iterator AI = FI->arg_begin(),
728 AE = FI->arg_end(); AI != AE; ++AI) {
729 printType(AI->getType());
732 // Add all of the basic blocks and instructions
733 for (Function::const_iterator BB = FI->begin(),
734 E = FI->end(); BB != E; ++BB) {
735 printType(BB->getType());
736 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
738 printType(I->getType());
739 for (unsigned i = 0; i < I->getNumOperands(); ++i)
740 printType(I->getOperand(i)->getType());
747 // printConstant - Print out a constant pool entry...
748 void CppWriter::printConstant(const Constant *CV) {
749 // First, if the constant is actually a GlobalValue (variable or function)
750 // or its already in the constant list then we've printed it already and we
752 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
755 std::string constName(getCppName(CV));
756 std::string typeName(getCppName(CV->getType()));
758 if (isa<GlobalValue>(CV)) {
759 // Skip variables and functions, we emit them elsewhere
763 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
764 std::string constValue = CI->getValue().toString(10, true);
765 Out << "ConstantInt* " << constName
766 << " = ConstantInt::get(mod->getContext(), APInt("
767 << cast<IntegerType>(CI->getType())->getBitWidth()
768 << ", StringRef(\"" << constValue << "\"), 10));";
769 } else if (isa<ConstantAggregateZero>(CV)) {
770 Out << "ConstantAggregateZero* " << constName
771 << " = ConstantAggregateZero::get(" << typeName << ");";
772 } else if (isa<ConstantPointerNull>(CV)) {
773 Out << "ConstantPointerNull* " << constName
774 << " = ConstantPointerNull::get(" << typeName << ");";
775 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
776 Out << "ConstantFP* " << constName << " = ";
779 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
780 if (CA->isString() &&
781 CA->getType()->getElementType() ==
782 Type::getInt8Ty(CA->getContext())) {
783 Out << "Constant* " << constName <<
784 " = ConstantArray::get(mod->getContext(), \"";
785 std::string tmp = CA->getAsString();
786 bool nullTerminate = false;
787 if (tmp[tmp.length()-1] == 0) {
788 tmp.erase(tmp.length()-1);
789 nullTerminate = true;
791 printEscapedString(tmp);
792 // Determine if we want null termination or not.
794 Out << "\", true"; // Indicate that the null terminator should be
797 Out << "\", false";// No null terminator
800 Out << "std::vector<Constant*> " << constName << "_elems;";
802 unsigned N = CA->getNumOperands();
803 for (unsigned i = 0; i < N; ++i) {
804 printConstant(CA->getOperand(i)); // recurse to print operands
805 Out << constName << "_elems.push_back("
806 << getCppName(CA->getOperand(i)) << ");";
809 Out << "Constant* " << constName << " = ConstantArray::get("
810 << typeName << ", " << constName << "_elems);";
812 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
813 Out << "std::vector<Constant*> " << constName << "_fields;";
815 unsigned N = CS->getNumOperands();
816 for (unsigned i = 0; i < N; i++) {
817 printConstant(CS->getOperand(i));
818 Out << constName << "_fields.push_back("
819 << getCppName(CS->getOperand(i)) << ");";
822 Out << "Constant* " << constName << " = ConstantStruct::get("
823 << typeName << ", " << constName << "_fields);";
824 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
825 Out << "std::vector<Constant*> " << constName << "_elems;";
827 unsigned N = CP->getNumOperands();
828 for (unsigned i = 0; i < N; ++i) {
829 printConstant(CP->getOperand(i));
830 Out << constName << "_elems.push_back("
831 << getCppName(CP->getOperand(i)) << ");";
834 Out << "Constant* " << constName << " = ConstantVector::get("
835 << typeName << ", " << constName << "_elems);";
836 } else if (isa<UndefValue>(CV)) {
837 Out << "UndefValue* " << constName << " = UndefValue::get("
839 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
840 if (CE->getOpcode() == Instruction::GetElementPtr) {
841 Out << "std::vector<Constant*> " << constName << "_indices;";
843 printConstant(CE->getOperand(0));
844 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
845 printConstant(CE->getOperand(i));
846 Out << constName << "_indices.push_back("
847 << getCppName(CE->getOperand(i)) << ");";
850 Out << "Constant* " << constName
851 << " = ConstantExpr::getGetElementPtr("
852 << getCppName(CE->getOperand(0)) << ", "
853 << "&" << constName << "_indices[0], "
854 << constName << "_indices.size()"
856 } else if (CE->isCast()) {
857 printConstant(CE->getOperand(0));
858 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
859 switch (CE->getOpcode()) {
860 default: llvm_unreachable("Invalid cast opcode");
861 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
862 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
863 case Instruction::SExt: Out << "Instruction::SExt"; break;
864 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
865 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
866 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
867 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
868 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
869 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
870 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
871 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
872 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
874 Out << ", " << getCppName(CE->getOperand(0)) << ", "
875 << getCppName(CE->getType()) << ");";
877 unsigned N = CE->getNumOperands();
878 for (unsigned i = 0; i < N; ++i ) {
879 printConstant(CE->getOperand(i));
881 Out << "Constant* " << constName << " = ConstantExpr::";
882 switch (CE->getOpcode()) {
883 case Instruction::Add: Out << "getAdd("; break;
884 case Instruction::FAdd: Out << "getFAdd("; break;
885 case Instruction::Sub: Out << "getSub("; break;
886 case Instruction::FSub: Out << "getFSub("; break;
887 case Instruction::Mul: Out << "getMul("; break;
888 case Instruction::FMul: Out << "getFMul("; break;
889 case Instruction::UDiv: Out << "getUDiv("; break;
890 case Instruction::SDiv: Out << "getSDiv("; break;
891 case Instruction::FDiv: Out << "getFDiv("; break;
892 case Instruction::URem: Out << "getURem("; break;
893 case Instruction::SRem: Out << "getSRem("; break;
894 case Instruction::FRem: Out << "getFRem("; break;
895 case Instruction::And: Out << "getAnd("; break;
896 case Instruction::Or: Out << "getOr("; break;
897 case Instruction::Xor: Out << "getXor("; break;
898 case Instruction::ICmp:
899 Out << "getICmp(ICmpInst::ICMP_";
900 switch (CE->getPredicate()) {
901 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
902 case ICmpInst::ICMP_NE: Out << "NE"; break;
903 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
904 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
905 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
906 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
907 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
908 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
909 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
910 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
911 default: error("Invalid ICmp Predicate");
914 case Instruction::FCmp:
915 Out << "getFCmp(FCmpInst::FCMP_";
916 switch (CE->getPredicate()) {
917 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
918 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
919 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
920 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
921 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
922 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
923 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
924 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
925 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
926 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
927 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
928 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
929 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
930 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
931 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
932 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
933 default: error("Invalid FCmp Predicate");
936 case Instruction::Shl: Out << "getShl("; break;
937 case Instruction::LShr: Out << "getLShr("; break;
938 case Instruction::AShr: Out << "getAShr("; break;
939 case Instruction::Select: Out << "getSelect("; break;
940 case Instruction::ExtractElement: Out << "getExtractElement("; break;
941 case Instruction::InsertElement: Out << "getInsertElement("; break;
942 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
944 error("Invalid constant expression");
947 Out << getCppName(CE->getOperand(0));
948 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
949 Out << ", " << getCppName(CE->getOperand(i));
952 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
953 Out << "Constant* " << constName << " = ";
954 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
956 error("Bad Constant");
957 Out << "Constant* " << constName << " = 0; ";
962 void CppWriter::printConstants(const Module* M) {
963 // Traverse all the global variables looking for constant initializers
964 for (Module::const_global_iterator I = TheModule->global_begin(),
965 E = TheModule->global_end(); I != E; ++I)
966 if (I->hasInitializer())
967 printConstant(I->getInitializer());
969 // Traverse the LLVM functions looking for constants
970 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
972 // Add all of the basic blocks and instructions
973 for (Function::const_iterator BB = FI->begin(),
974 E = FI->end(); BB != E; ++BB) {
975 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
977 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
978 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
987 void CppWriter::printVariableUses(const GlobalVariable *GV) {
988 nl(Out) << "// Type Definitions";
990 printType(GV->getType());
991 if (GV->hasInitializer()) {
992 Constant *Init = GV->getInitializer();
993 printType(Init->getType());
994 if (Function *F = dyn_cast<Function>(Init)) {
995 nl(Out)<< "/ Function Declarations"; nl(Out);
996 printFunctionHead(F);
997 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
998 nl(Out) << "// Global Variable Declarations"; nl(Out);
999 printVariableHead(gv);
1001 nl(Out) << "// Global Variable Definitions"; nl(Out);
1002 printVariableBody(gv);
1004 nl(Out) << "// Constant Definitions"; nl(Out);
1005 printConstant(Init);
1010 void CppWriter::printVariableHead(const GlobalVariable *GV) {
1011 nl(Out) << "GlobalVariable* " << getCppName(GV);
1013 Out << " = mod->getGlobalVariable(mod->getContext(), ";
1014 printEscapedString(GV->getName());
1015 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
1016 nl(Out) << "if (!" << getCppName(GV) << ") {";
1017 in(); nl(Out) << getCppName(GV);
1019 Out << " = new GlobalVariable(/*Module=*/*mod, ";
1020 nl(Out) << "/*Type=*/";
1021 printCppName(GV->getType()->getElementType());
1023 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1025 nl(Out) << "/*Linkage=*/";
1026 printLinkageType(GV->getLinkage());
1028 nl(Out) << "/*Initializer=*/0, ";
1029 if (GV->hasInitializer()) {
1030 Out << "// has initializer, specified below";
1032 nl(Out) << "/*Name=*/\"";
1033 printEscapedString(GV->getName());
1037 if (GV->hasSection()) {
1039 Out << "->setSection(\"";
1040 printEscapedString(GV->getSection());
1044 if (GV->getAlignment()) {
1046 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1049 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1051 Out << "->setVisibility(";
1052 printVisibilityType(GV->getVisibility());
1056 if (GV->isThreadLocal()) {
1058 Out << "->setThreadLocal(true);";
1062 out(); Out << "}"; nl(Out);
1066 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1067 if (GV->hasInitializer()) {
1069 Out << "->setInitializer(";
1070 Out << getCppName(GV->getInitializer()) << ");";
1075 std::string CppWriter::getOpName(Value* V) {
1076 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1077 return getCppName(V);
1079 // See if its alread in the map of forward references, if so just return the
1080 // name we already set up for it
1081 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1082 if (I != ForwardRefs.end())
1085 // This is a new forward reference. Generate a unique name for it
1086 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1088 // Yes, this is a hack. An Argument is the smallest instantiable value that
1089 // we can make as a placeholder for the real value. We'll replace these
1090 // Argument instances later.
1091 Out << "Argument* " << result << " = new Argument("
1092 << getCppName(V->getType()) << ");";
1094 ForwardRefs[V] = result;
1098 // printInstruction - This member is called for each Instruction in a function.
1099 void CppWriter::printInstruction(const Instruction *I,
1100 const std::string& bbname) {
1101 std::string iName(getCppName(I));
1103 // Before we emit this instruction, we need to take care of generating any
1104 // forward references. So, we get the names of all the operands in advance
1105 const unsigned Ops(I->getNumOperands());
1106 std::string* opNames = new std::string[Ops];
1107 for (unsigned i = 0; i < Ops; i++)
1108 opNames[i] = getOpName(I->getOperand(i));
1110 switch (I->getOpcode()) {
1112 error("Invalid instruction");
1115 case Instruction::Ret: {
1116 const ReturnInst* ret = cast<ReturnInst>(I);
1117 Out << "ReturnInst::Create(mod->getContext(), "
1118 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1121 case Instruction::Br: {
1122 const BranchInst* br = cast<BranchInst>(I);
1123 Out << "BranchInst::Create(" ;
1124 if (br->getNumOperands() == 3) {
1125 Out << opNames[2] << ", "
1126 << opNames[1] << ", "
1127 << opNames[0] << ", ";
1129 } else if (br->getNumOperands() == 1) {
1130 Out << opNames[0] << ", ";
1132 error("Branch with 2 operands?");
1134 Out << bbname << ");";
1137 case Instruction::Switch: {
1138 const SwitchInst *SI = cast<SwitchInst>(I);
1139 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1140 << opNames[0] << ", "
1141 << opNames[1] << ", "
1142 << SI->getNumCases() << ", " << bbname << ");";
1144 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
1145 Out << iName << "->addCase("
1146 << opNames[i] << ", "
1147 << opNames[i+1] << ");";
1152 case Instruction::IndirectBr: {
1153 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1154 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1155 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1157 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1158 Out << iName << "->addDestination(" << opNames[i] << ");";
1163 case Instruction::Invoke: {
1164 const InvokeInst* inv = cast<InvokeInst>(I);
1165 Out << "std::vector<Value*> " << iName << "_params;";
1167 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1168 Out << iName << "_params.push_back("
1169 << getOpName(inv->getArgOperand(i)) << ");";
1172 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1173 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1174 << getOpName(inv->getCalledFunction()) << ", "
1175 << getOpName(inv->getNormalDest()) << ", "
1176 << getOpName(inv->getUnwindDest()) << ", "
1177 << iName << "_params.begin(), "
1178 << iName << "_params.end(), \"";
1179 printEscapedString(inv->getName());
1180 Out << "\", " << bbname << ");";
1181 nl(Out) << iName << "->setCallingConv(";
1182 printCallingConv(inv->getCallingConv());
1184 printAttributes(inv->getAttributes(), iName);
1185 Out << iName << "->setAttributes(" << iName << "_PAL);";
1189 case Instruction::Unwind: {
1190 Out << "new UnwindInst("
1194 case Instruction::Unreachable: {
1195 Out << "new UnreachableInst("
1196 << "mod->getContext(), "
1200 case Instruction::Add:
1201 case Instruction::FAdd:
1202 case Instruction::Sub:
1203 case Instruction::FSub:
1204 case Instruction::Mul:
1205 case Instruction::FMul:
1206 case Instruction::UDiv:
1207 case Instruction::SDiv:
1208 case Instruction::FDiv:
1209 case Instruction::URem:
1210 case Instruction::SRem:
1211 case Instruction::FRem:
1212 case Instruction::And:
1213 case Instruction::Or:
1214 case Instruction::Xor:
1215 case Instruction::Shl:
1216 case Instruction::LShr:
1217 case Instruction::AShr:{
1218 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1219 switch (I->getOpcode()) {
1220 case Instruction::Add: Out << "Instruction::Add"; break;
1221 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1222 case Instruction::Sub: Out << "Instruction::Sub"; break;
1223 case Instruction::FSub: Out << "Instruction::FSub"; break;
1224 case Instruction::Mul: Out << "Instruction::Mul"; break;
1225 case Instruction::FMul: Out << "Instruction::FMul"; break;
1226 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1227 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1228 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1229 case Instruction::URem:Out << "Instruction::URem"; break;
1230 case Instruction::SRem:Out << "Instruction::SRem"; break;
1231 case Instruction::FRem:Out << "Instruction::FRem"; break;
1232 case Instruction::And: Out << "Instruction::And"; break;
1233 case Instruction::Or: Out << "Instruction::Or"; break;
1234 case Instruction::Xor: Out << "Instruction::Xor"; break;
1235 case Instruction::Shl: Out << "Instruction::Shl"; break;
1236 case Instruction::LShr:Out << "Instruction::LShr"; break;
1237 case Instruction::AShr:Out << "Instruction::AShr"; break;
1238 default: Out << "Instruction::BadOpCode"; break;
1240 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1241 printEscapedString(I->getName());
1242 Out << "\", " << bbname << ");";
1245 case Instruction::FCmp: {
1246 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1247 switch (cast<FCmpInst>(I)->getPredicate()) {
1248 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1249 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1250 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1251 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1252 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1253 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1254 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1255 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1256 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1257 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1258 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1259 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1260 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1261 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1262 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1263 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1264 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1266 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1267 printEscapedString(I->getName());
1271 case Instruction::ICmp: {
1272 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1273 switch (cast<ICmpInst>(I)->getPredicate()) {
1274 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1275 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1276 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1277 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1278 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1279 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1280 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1281 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1282 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1283 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1284 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1286 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1287 printEscapedString(I->getName());
1291 case Instruction::Alloca: {
1292 const AllocaInst* allocaI = cast<AllocaInst>(I);
1293 Out << "AllocaInst* " << iName << " = new AllocaInst("
1294 << getCppName(allocaI->getAllocatedType()) << ", ";
1295 if (allocaI->isArrayAllocation())
1296 Out << opNames[0] << ", ";
1298 printEscapedString(allocaI->getName());
1299 Out << "\", " << bbname << ");";
1300 if (allocaI->getAlignment())
1301 nl(Out) << iName << "->setAlignment("
1302 << allocaI->getAlignment() << ");";
1305 case Instruction::Load: {
1306 const LoadInst* load = cast<LoadInst>(I);
1307 Out << "LoadInst* " << iName << " = new LoadInst("
1308 << opNames[0] << ", \"";
1309 printEscapedString(load->getName());
1310 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1311 << ", " << bbname << ");";
1314 case Instruction::Store: {
1315 const StoreInst* store = cast<StoreInst>(I);
1316 Out << " new StoreInst("
1317 << opNames[0] << ", "
1318 << opNames[1] << ", "
1319 << (store->isVolatile() ? "true" : "false")
1320 << ", " << bbname << ");";
1323 case Instruction::GetElementPtr: {
1324 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1325 if (gep->getNumOperands() <= 2) {
1326 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1328 if (gep->getNumOperands() == 2)
1329 Out << ", " << opNames[1];
1331 Out << "std::vector<Value*> " << iName << "_indices;";
1333 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1334 Out << iName << "_indices.push_back("
1335 << opNames[i] << ");";
1338 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1339 << opNames[0] << ", " << iName << "_indices.begin(), "
1340 << iName << "_indices.end()";
1343 printEscapedString(gep->getName());
1344 Out << "\", " << bbname << ");";
1347 case Instruction::PHI: {
1348 const PHINode* phi = cast<PHINode>(I);
1350 Out << "PHINode* " << iName << " = PHINode::Create("
1351 << getCppName(phi->getType()) << ", "
1352 << phi->getNumIncomingValues() << ", \"";
1353 printEscapedString(phi->getName());
1354 Out << "\", " << bbname << ");";
1356 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1357 Out << iName << "->addIncoming("
1358 << opNames[i] << ", " << opNames[i+1] << ");";
1363 case Instruction::Trunc:
1364 case Instruction::ZExt:
1365 case Instruction::SExt:
1366 case Instruction::FPTrunc:
1367 case Instruction::FPExt:
1368 case Instruction::FPToUI:
1369 case Instruction::FPToSI:
1370 case Instruction::UIToFP:
1371 case Instruction::SIToFP:
1372 case Instruction::PtrToInt:
1373 case Instruction::IntToPtr:
1374 case Instruction::BitCast: {
1375 const CastInst* cst = cast<CastInst>(I);
1376 Out << "CastInst* " << iName << " = new ";
1377 switch (I->getOpcode()) {
1378 case Instruction::Trunc: Out << "TruncInst"; break;
1379 case Instruction::ZExt: Out << "ZExtInst"; break;
1380 case Instruction::SExt: Out << "SExtInst"; break;
1381 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1382 case Instruction::FPExt: Out << "FPExtInst"; break;
1383 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1384 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1385 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1386 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1387 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1388 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1389 case Instruction::BitCast: Out << "BitCastInst"; break;
1390 default: assert(!"Unreachable"); break;
1392 Out << "(" << opNames[0] << ", "
1393 << getCppName(cst->getType()) << ", \"";
1394 printEscapedString(cst->getName());
1395 Out << "\", " << bbname << ");";
1398 case Instruction::Call: {
1399 const CallInst* call = cast<CallInst>(I);
1400 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1401 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1402 << getCppName(ila->getFunctionType()) << ", \""
1403 << ila->getAsmString() << "\", \""
1404 << ila->getConstraintString() << "\","
1405 << (ila->hasSideEffects() ? "true" : "false") << ");";
1408 if (call->getNumArgOperands() > 1) {
1409 Out << "std::vector<Value*> " << iName << "_params;";
1411 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
1412 Out << iName << "_params.push_back(" << opNames[i] << ");";
1415 Out << "CallInst* " << iName << " = CallInst::Create("
1416 << opNames[call->getNumArgOperands()] << ", "
1417 << iName << "_params.begin(), "
1418 << iName << "_params.end(), \"";
1419 } else if (call->getNumArgOperands() == 1) {
1420 Out << "CallInst* " << iName << " = CallInst::Create("
1421 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
1423 Out << "CallInst* " << iName << " = CallInst::Create("
1424 << opNames[call->getNumArgOperands()] << ", \"";
1426 printEscapedString(call->getName());
1427 Out << "\", " << bbname << ");";
1428 nl(Out) << iName << "->setCallingConv(";
1429 printCallingConv(call->getCallingConv());
1431 nl(Out) << iName << "->setTailCall("
1432 << (call->isTailCall() ? "true" : "false");
1435 printAttributes(call->getAttributes(), iName);
1436 Out << iName << "->setAttributes(" << iName << "_PAL);";
1440 case Instruction::Select: {
1441 const SelectInst* sel = cast<SelectInst>(I);
1442 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1443 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1444 printEscapedString(sel->getName());
1445 Out << "\", " << bbname << ");";
1448 case Instruction::UserOp1:
1450 case Instruction::UserOp2: {
1451 /// FIXME: What should be done here?
1454 case Instruction::VAArg: {
1455 const VAArgInst* va = cast<VAArgInst>(I);
1456 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1457 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1458 printEscapedString(va->getName());
1459 Out << "\", " << bbname << ");";
1462 case Instruction::ExtractElement: {
1463 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1464 Out << "ExtractElementInst* " << getCppName(eei)
1465 << " = new ExtractElementInst(" << opNames[0]
1466 << ", " << opNames[1] << ", \"";
1467 printEscapedString(eei->getName());
1468 Out << "\", " << bbname << ");";
1471 case Instruction::InsertElement: {
1472 const InsertElementInst* iei = cast<InsertElementInst>(I);
1473 Out << "InsertElementInst* " << getCppName(iei)
1474 << " = InsertElementInst::Create(" << opNames[0]
1475 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1476 printEscapedString(iei->getName());
1477 Out << "\", " << bbname << ");";
1480 case Instruction::ShuffleVector: {
1481 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1482 Out << "ShuffleVectorInst* " << getCppName(svi)
1483 << " = new ShuffleVectorInst(" << opNames[0]
1484 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1485 printEscapedString(svi->getName());
1486 Out << "\", " << bbname << ");";
1489 case Instruction::ExtractValue: {
1490 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1491 Out << "std::vector<unsigned> " << iName << "_indices;";
1493 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1494 Out << iName << "_indices.push_back("
1495 << evi->idx_begin()[i] << ");";
1498 Out << "ExtractValueInst* " << getCppName(evi)
1499 << " = ExtractValueInst::Create(" << opNames[0]
1501 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1502 printEscapedString(evi->getName());
1503 Out << "\", " << bbname << ");";
1506 case Instruction::InsertValue: {
1507 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1508 Out << "std::vector<unsigned> " << iName << "_indices;";
1510 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1511 Out << iName << "_indices.push_back("
1512 << ivi->idx_begin()[i] << ");";
1515 Out << "InsertValueInst* " << getCppName(ivi)
1516 << " = InsertValueInst::Create(" << opNames[0]
1517 << ", " << opNames[1] << ", "
1518 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1519 printEscapedString(ivi->getName());
1520 Out << "\", " << bbname << ");";
1524 DefinedValues.insert(I);
1529 // Print out the types, constants and declarations needed by one function
1530 void CppWriter::printFunctionUses(const Function* F) {
1531 nl(Out) << "// Type Definitions"; nl(Out);
1533 // Print the function's return type
1534 printType(F->getReturnType());
1536 // Print the function's function type
1537 printType(F->getFunctionType());
1539 // Print the types of each of the function's arguments
1540 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1542 printType(AI->getType());
1546 // Print type definitions for every type referenced by an instruction and
1547 // make a note of any global values or constants that are referenced
1548 SmallPtrSet<GlobalValue*,64> gvs;
1549 SmallPtrSet<Constant*,64> consts;
1550 for (Function::const_iterator BB = F->begin(), BE = F->end();
1552 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1554 // Print the type of the instruction itself
1555 printType(I->getType());
1557 // Print the type of each of the instruction's operands
1558 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1559 Value* operand = I->getOperand(i);
1560 printType(operand->getType());
1562 // If the operand references a GVal or Constant, make a note of it
1563 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1565 if (GenerationType != GenFunction)
1566 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1567 if (GVar->hasInitializer())
1568 consts.insert(GVar->getInitializer());
1569 } else if (Constant* C = dyn_cast<Constant>(operand)) {
1571 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1572 // If the operand references a GVal or Constant, make a note of it
1573 Value* operand = C->getOperand(j);
1574 printType(operand->getType());
1575 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1577 if (GenerationType != GenFunction)
1578 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1579 if (GVar->hasInitializer())
1580 consts.insert(GVar->getInitializer());
1588 // Print the function declarations for any functions encountered
1589 nl(Out) << "// Function Declarations"; nl(Out);
1590 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1592 if (Function* Fun = dyn_cast<Function>(*I)) {
1593 if (!is_inline || Fun != F)
1594 printFunctionHead(Fun);
1598 // Print the global variable declarations for any variables encountered
1599 nl(Out) << "// Global Variable Declarations"; nl(Out);
1600 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1602 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1603 printVariableHead(F);
1606 // Print the constants found
1607 nl(Out) << "// Constant Definitions"; nl(Out);
1608 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1609 E = consts.end(); I != E; ++I) {
1613 // Process the global variables definitions now that all the constants have
1614 // been emitted. These definitions just couple the gvars with their constant
1616 if (GenerationType != GenFunction) {
1617 nl(Out) << "// Global Variable Definitions"; nl(Out);
1618 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1620 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1621 printVariableBody(GV);
1626 void CppWriter::printFunctionHead(const Function* F) {
1627 nl(Out) << "Function* " << getCppName(F);
1629 Out << " = mod->getFunction(\"";
1630 printEscapedString(F->getName());
1631 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1632 nl(Out) << "if (!" << getCppName(F) << ") {";
1633 nl(Out) << getCppName(F);
1635 Out<< " = Function::Create(";
1636 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1637 nl(Out) << "/*Linkage=*/";
1638 printLinkageType(F->getLinkage());
1640 nl(Out) << "/*Name=*/\"";
1641 printEscapedString(F->getName());
1642 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1645 Out << "->setCallingConv(";
1646 printCallingConv(F->getCallingConv());
1649 if (F->hasSection()) {
1651 Out << "->setSection(\"" << F->getSection() << "\");";
1654 if (F->getAlignment()) {
1656 Out << "->setAlignment(" << F->getAlignment() << ");";
1659 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1661 Out << "->setVisibility(";
1662 printVisibilityType(F->getVisibility());
1668 Out << "->setGC(\"" << F->getGC() << "\");";
1675 printAttributes(F->getAttributes(), getCppName(F));
1677 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1681 void CppWriter::printFunctionBody(const Function *F) {
1682 if (F->isDeclaration())
1683 return; // external functions have no bodies.
1685 // Clear the DefinedValues and ForwardRefs maps because we can't have
1686 // cross-function forward refs
1687 ForwardRefs.clear();
1688 DefinedValues.clear();
1690 // Create all the argument values
1692 if (!F->arg_empty()) {
1693 Out << "Function::arg_iterator args = " << getCppName(F)
1694 << "->arg_begin();";
1697 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1699 Out << "Value* " << getCppName(AI) << " = args++;";
1701 if (AI->hasName()) {
1702 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1708 // Create all the basic blocks
1710 for (Function::const_iterator BI = F->begin(), BE = F->end();
1712 std::string bbname(getCppName(BI));
1713 Out << "BasicBlock* " << bbname <<
1714 " = BasicBlock::Create(mod->getContext(), \"";
1716 printEscapedString(BI->getName());
1717 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1721 // Output all of its basic blocks... for the function
1722 for (Function::const_iterator BI = F->begin(), BE = F->end();
1724 std::string bbname(getCppName(BI));
1725 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1728 // Output all of the instructions in the basic block...
1729 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1731 printInstruction(I,bbname);
1735 // Loop over the ForwardRefs and resolve them now that all instructions
1737 if (!ForwardRefs.empty()) {
1738 nl(Out) << "// Resolve Forward References";
1742 while (!ForwardRefs.empty()) {
1743 ForwardRefMap::iterator I = ForwardRefs.begin();
1744 Out << I->second << "->replaceAllUsesWith("
1745 << getCppName(I->first) << "); delete " << I->second << ";";
1747 ForwardRefs.erase(I);
1751 void CppWriter::printInline(const std::string& fname,
1752 const std::string& func) {
1753 const Function* F = TheModule->getFunction(func);
1755 error(std::string("Function '") + func + "' not found in input module");
1758 if (F->isDeclaration()) {
1759 error(std::string("Function '") + func + "' is external!");
1762 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1764 unsigned arg_count = 1;
1765 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1767 Out << ", Value* arg_" << arg_count;
1772 printFunctionUses(F);
1773 printFunctionBody(F);
1775 Out << "return " << getCppName(F->begin()) << ";";
1780 void CppWriter::printModuleBody() {
1781 // Print out all the type definitions
1782 nl(Out) << "// Type Definitions"; nl(Out);
1783 printTypes(TheModule);
1785 // Functions can call each other and global variables can reference them so
1786 // define all the functions first before emitting their function bodies.
1787 nl(Out) << "// Function Declarations"; nl(Out);
1788 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1790 printFunctionHead(I);
1792 // Process the global variables declarations. We can't initialze them until
1793 // after the constants are printed so just print a header for each global
1794 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1795 for (Module::const_global_iterator I = TheModule->global_begin(),
1796 E = TheModule->global_end(); I != E; ++I) {
1797 printVariableHead(I);
1800 // Print out all the constants definitions. Constants don't recurse except
1801 // through GlobalValues. All GlobalValues have been declared at this point
1802 // so we can proceed to generate the constants.
1803 nl(Out) << "// Constant Definitions"; nl(Out);
1804 printConstants(TheModule);
1806 // Process the global variables definitions now that all the constants have
1807 // been emitted. These definitions just couple the gvars with their constant
1809 nl(Out) << "// Global Variable Definitions"; nl(Out);
1810 for (Module::const_global_iterator I = TheModule->global_begin(),
1811 E = TheModule->global_end(); I != E; ++I) {
1812 printVariableBody(I);
1815 // Finally, we can safely put out all of the function bodies.
1816 nl(Out) << "// Function Definitions"; nl(Out);
1817 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1819 if (!I->isDeclaration()) {
1820 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1824 printFunctionBody(I);
1831 void CppWriter::printProgram(const std::string& fname,
1832 const std::string& mName) {
1833 Out << "#include <llvm/LLVMContext.h>\n";
1834 Out << "#include <llvm/Module.h>\n";
1835 Out << "#include <llvm/DerivedTypes.h>\n";
1836 Out << "#include <llvm/Constants.h>\n";
1837 Out << "#include <llvm/GlobalVariable.h>\n";
1838 Out << "#include <llvm/Function.h>\n";
1839 Out << "#include <llvm/CallingConv.h>\n";
1840 Out << "#include <llvm/BasicBlock.h>\n";
1841 Out << "#include <llvm/Instructions.h>\n";
1842 Out << "#include <llvm/InlineAsm.h>\n";
1843 Out << "#include <llvm/Support/FormattedStream.h>\n";
1844 Out << "#include <llvm/Support/MathExtras.h>\n";
1845 Out << "#include <llvm/Pass.h>\n";
1846 Out << "#include <llvm/PassManager.h>\n";
1847 Out << "#include <llvm/ADT/SmallVector.h>\n";
1848 Out << "#include <llvm/Analysis/Verifier.h>\n";
1849 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1850 Out << "#include <algorithm>\n";
1851 Out << "using namespace llvm;\n\n";
1852 Out << "Module* " << fname << "();\n\n";
1853 Out << "int main(int argc, char**argv) {\n";
1854 Out << " Module* Mod = " << fname << "();\n";
1855 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1856 Out << " PassManager PM;\n";
1857 Out << " PM.add(createPrintModulePass(&outs()));\n";
1858 Out << " PM.run(*Mod);\n";
1859 Out << " return 0;\n";
1861 printModule(fname,mName);
1864 void CppWriter::printModule(const std::string& fname,
1865 const std::string& mName) {
1866 nl(Out) << "Module* " << fname << "() {";
1867 nl(Out,1) << "// Module Construction";
1868 nl(Out) << "Module* mod = new Module(\"";
1869 printEscapedString(mName);
1870 Out << "\", getGlobalContext());";
1871 if (!TheModule->getTargetTriple().empty()) {
1872 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1874 if (!TheModule->getTargetTriple().empty()) {
1875 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1879 if (!TheModule->getModuleInlineAsm().empty()) {
1880 nl(Out) << "mod->setModuleInlineAsm(\"";
1881 printEscapedString(TheModule->getModuleInlineAsm());
1886 // Loop over the dependent libraries and emit them.
1887 Module::lib_iterator LI = TheModule->lib_begin();
1888 Module::lib_iterator LE = TheModule->lib_end();
1890 Out << "mod->addLibrary(\"" << *LI << "\");";
1895 nl(Out) << "return mod;";
1900 void CppWriter::printContents(const std::string& fname,
1901 const std::string& mName) {
1902 Out << "\nModule* " << fname << "(Module *mod) {\n";
1903 Out << "\nmod->setModuleIdentifier(\"";
1904 printEscapedString(mName);
1907 Out << "\nreturn mod;\n";
1911 void CppWriter::printFunction(const std::string& fname,
1912 const std::string& funcName) {
1913 const Function* F = TheModule->getFunction(funcName);
1915 error(std::string("Function '") + funcName + "' not found in input module");
1918 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1919 printFunctionUses(F);
1920 printFunctionHead(F);
1921 printFunctionBody(F);
1922 Out << "return " << getCppName(F) << ";\n";
1926 void CppWriter::printFunctions() {
1927 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1928 Module::const_iterator I = funcs.begin();
1929 Module::const_iterator IE = funcs.end();
1931 for (; I != IE; ++I) {
1932 const Function &func = *I;
1933 if (!func.isDeclaration()) {
1934 std::string name("define_");
1935 name += func.getName();
1936 printFunction(name, func.getName());
1941 void CppWriter::printVariable(const std::string& fname,
1942 const std::string& varName) {
1943 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1946 error(std::string("Variable '") + varName + "' not found in input module");
1949 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1950 printVariableUses(GV);
1951 printVariableHead(GV);
1952 printVariableBody(GV);
1953 Out << "return " << getCppName(GV) << ";\n";
1957 void CppWriter::printType(const std::string& fname,
1958 const std::string& typeName) {
1959 const Type* Ty = TheModule->getTypeByName(typeName);
1961 error(std::string("Type '") + typeName + "' not found in input module");
1964 Out << "\nType* " << fname << "(Module *mod) {\n";
1966 Out << "return " << getCppName(Ty) << ";\n";
1970 bool CppWriter::runOnModule(Module &M) {
1974 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1976 // Get the name of the function we're supposed to generate
1977 std::string fname = FuncName.getValue();
1979 // Get the name of the thing we are to generate
1980 std::string tgtname = NameToGenerate.getValue();
1981 if (GenerationType == GenModule ||
1982 GenerationType == GenContents ||
1983 GenerationType == GenProgram ||
1984 GenerationType == GenFunctions) {
1985 if (tgtname == "!bad!") {
1986 if (M.getModuleIdentifier() == "-")
1987 tgtname = "<stdin>";
1989 tgtname = M.getModuleIdentifier();
1991 } else if (tgtname == "!bad!")
1992 error("You must use the -for option with -gen-{function,variable,type}");
1994 switch (WhatToGenerate(GenerationType)) {
1997 fname = "makeLLVMModule";
1998 printProgram(fname,tgtname);
2002 fname = "makeLLVMModule";
2003 printModule(fname,tgtname);
2007 fname = "makeLLVMModuleContents";
2008 printContents(fname,tgtname);
2012 fname = "makeLLVMFunction";
2013 printFunction(fname,tgtname);
2020 fname = "makeLLVMInline";
2021 printInline(fname,tgtname);
2025 fname = "makeLLVMVariable";
2026 printVariable(fname,tgtname);
2030 fname = "makeLLVMType";
2031 printType(fname,tgtname);
2034 error("Invalid generation option");
2040 char CppWriter::ID = 0;
2042 //===----------------------------------------------------------------------===//
2043 // External Interface declaration
2044 //===----------------------------------------------------------------------===//
2046 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2047 formatted_raw_ostream &o,
2048 CodeGenFileType FileType,
2049 CodeGenOpt::Level OptLevel,
2050 bool DisableVerify) {
2051 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
2052 PM.add(new CppWriter(o));