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/Target/TargetMachineRegistry.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Streams.h"
32 #include "llvm/Support/raw_ostream.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 /// CppBackendTargetMachineModule - Note that this is used on hosts
75 /// that cannot link in a library unless there are references into the
76 /// library. In particular, it seems that it is not possible to get
77 /// things to work on Win32 without this. Though it is unused, do not
79 extern "C" int CppBackendTargetMachineModule;
80 int CppBackendTargetMachineModule = 0;
82 // Register the target.
83 static RegisterTarget<CPPTargetMachine> X("cpp", "C++ backend");
86 typedef std::vector<const Type*> TypeList;
87 typedef std::map<const Type*,std::string> TypeMap;
88 typedef std::map<const Value*,std::string> ValueMap;
89 typedef std::set<std::string> NameSet;
90 typedef std::set<const Type*> TypeSet;
91 typedef std::set<const Value*> ValueSet;
92 typedef std::map<const Value*,std::string> ForwardRefMap;
94 /// CppWriter - This class is the main chunk of code that converts an LLVM
95 /// module to a C++ translation unit.
96 class CppWriter : public ModulePass {
99 const Module *TheModule;
103 TypeMap UnresolvedTypes;
106 TypeSet DefinedTypes;
107 ValueSet DefinedValues;
108 ForwardRefMap ForwardRefs;
113 explicit CppWriter(raw_ostream &o) :
114 ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
116 virtual const char *getPassName() const { return "C++ backend"; }
118 bool runOnModule(Module &M);
120 void printProgram(const std::string& fname, const std::string& modName );
121 void printModule(const std::string& fname, const std::string& modName );
122 void printContents(const std::string& fname, const std::string& modName );
123 void printFunction(const std::string& fname, const std::string& funcName );
124 void printFunctions();
125 void printInline(const std::string& fname, const std::string& funcName );
126 void printVariable(const std::string& fname, const std::string& varName );
127 void printType(const std::string& fname, const std::string& typeName );
129 void error(const std::string& msg);
132 void printLinkageType(GlobalValue::LinkageTypes LT);
133 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
134 void printCallingConv(unsigned cc);
135 void printEscapedString(const std::string& str);
136 void printCFP(const ConstantFP* CFP);
138 std::string getCppName(const Type* val);
139 inline void printCppName(const Type* val);
141 std::string getCppName(const Value* val);
142 inline void printCppName(const Value* val);
144 void printAttributes(const AttrListPtr &PAL, const std::string &name);
145 bool printTypeInternal(const Type* Ty);
146 inline void printType(const Type* Ty);
147 void printTypes(const Module* M);
149 void printConstant(const Constant *CPV);
150 void printConstants(const Module* M);
152 void printVariableUses(const GlobalVariable *GV);
153 void printVariableHead(const GlobalVariable *GV);
154 void printVariableBody(const GlobalVariable *GV);
156 void printFunctionUses(const Function *F);
157 void printFunctionHead(const Function *F);
158 void printFunctionBody(const Function *F);
159 void printInstruction(const Instruction *I, const std::string& bbname);
160 std::string getOpName(Value*);
162 void printModuleBody();
165 static unsigned indent_level = 0;
166 inline raw_ostream& nl(raw_ostream& Out, int delta = 0) {
168 if (delta >= 0 || indent_level >= unsigned(-delta))
169 indent_level += delta;
170 for (unsigned i = 0; i < indent_level; ++i)
175 inline void in() { indent_level++; }
176 inline void out() { if (indent_level >0) indent_level--; }
179 sanitize(std::string& str) {
180 for (size_t i = 0; i < str.length(); ++i)
181 if (!isalnum(str[i]) && str[i] != '_')
186 getTypePrefix(const Type* Ty ) {
187 switch (Ty->getTypeID()) {
188 case Type::VoidTyID: return "void_";
189 case Type::IntegerTyID:
190 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
192 case Type::FloatTyID: return "float_";
193 case Type::DoubleTyID: return "double_";
194 case Type::LabelTyID: return "label_";
195 case Type::FunctionTyID: return "func_";
196 case Type::StructTyID: return "struct_";
197 case Type::ArrayTyID: return "array_";
198 case Type::PointerTyID: return "ptr_";
199 case Type::VectorTyID: return "packed_";
200 case Type::OpaqueTyID: return "opaque_";
201 default: return "other_";
206 // Looks up the type in the symbol table and returns a pointer to its name or
207 // a null pointer if it wasn't found. Note that this isn't the same as the
208 // Mode::getTypeName function which will return an empty string, not a null
209 // pointer if the name is not found.
210 inline const std::string*
211 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
212 TypeSymbolTable::const_iterator TI = ST.begin();
213 TypeSymbolTable::const_iterator TE = ST.end();
214 for (;TI != TE; ++TI)
215 if (TI->second == Ty)
220 void CppWriter::error(const std::string& msg) {
221 cerr << progname << ": " << msg << "\n";
225 // printCFP - Print a floating point constant .. very carefully :)
226 // This makes sure that conversion to/from floating yields the same binary
227 // result so that we don't lose precision.
228 void CppWriter::printCFP(const ConstantFP *CFP) {
230 APFloat APF = APFloat(CFP->getValueAPF()); // copy
231 if (CFP->getType() == Type::FloatTy)
232 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
233 Out << "ConstantFP::get(";
237 sprintf(Buffer, "%A", APF.convertToDouble());
238 if ((!strncmp(Buffer, "0x", 2) ||
239 !strncmp(Buffer, "-0x", 3) ||
240 !strncmp(Buffer, "+0x", 3)) &&
241 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
242 if (CFP->getType() == Type::DoubleTy)
243 Out << "BitsToDouble(" << Buffer << ")";
245 Out << "BitsToFloat((float)" << Buffer << ")";
249 std::string StrVal = ftostr(CFP->getValueAPF());
251 while (StrVal[0] == ' ')
252 StrVal.erase(StrVal.begin());
254 // Check to make sure that the stringized number is not some string like
255 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
256 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
257 ((StrVal[0] == '-' || StrVal[0] == '+') &&
258 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
259 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
260 if (CFP->getType() == Type::DoubleTy)
263 Out << StrVal << "f";
264 } else if (CFP->getType() == Type::DoubleTy)
265 Out << "BitsToDouble(0x"
266 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
267 << "ULL) /* " << StrVal << " */";
269 Out << "BitsToFloat(0x"
270 << utohexstr((uint32_t)CFP->getValueAPF().
271 bitcastToAPInt().getZExtValue())
272 << "U) /* " << StrVal << " */";
280 void CppWriter::printCallingConv(unsigned cc){
281 // Print the calling convention.
283 case CallingConv::C: Out << "CallingConv::C"; break;
284 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
285 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
286 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
287 default: Out << cc; break;
291 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
293 case GlobalValue::InternalLinkage:
294 Out << "GlobalValue::InternalLinkage"; break;
295 case GlobalValue::LinkOnceLinkage:
296 Out << "GlobalValue::LinkOnceLinkage "; break;
297 case GlobalValue::WeakLinkage:
298 Out << "GlobalValue::WeakLinkage"; break;
299 case GlobalValue::AppendingLinkage:
300 Out << "GlobalValue::AppendingLinkage"; break;
301 case GlobalValue::ExternalLinkage:
302 Out << "GlobalValue::ExternalLinkage"; break;
303 case GlobalValue::DLLImportLinkage:
304 Out << "GlobalValue::DLLImportLinkage"; break;
305 case GlobalValue::DLLExportLinkage:
306 Out << "GlobalValue::DLLExportLinkage"; break;
307 case GlobalValue::ExternalWeakLinkage:
308 Out << "GlobalValue::ExternalWeakLinkage"; break;
309 case GlobalValue::GhostLinkage:
310 Out << "GlobalValue::GhostLinkage"; break;
311 case GlobalValue::CommonLinkage:
312 Out << "GlobalValue::CommonLinkage"; break;
316 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
318 default: assert(0 && "Unknown GVar visibility");
319 case GlobalValue::DefaultVisibility:
320 Out << "GlobalValue::DefaultVisibility";
322 case GlobalValue::HiddenVisibility:
323 Out << "GlobalValue::HiddenVisibility";
325 case GlobalValue::ProtectedVisibility:
326 Out << "GlobalValue::ProtectedVisibility";
331 // printEscapedString - Print each character of the specified string, escaping
332 // it if it is not printable or if it is an escape char.
333 void CppWriter::printEscapedString(const std::string &Str) {
334 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
335 unsigned char C = Str[i];
336 if (isprint(C) && C != '"' && C != '\\') {
340 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
341 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
346 std::string CppWriter::getCppName(const Type* Ty) {
347 // First, handle the primitive types .. easy
348 if (Ty->isPrimitiveType() || Ty->isInteger()) {
349 switch (Ty->getTypeID()) {
350 case Type::VoidTyID: return "Type::VoidTy";
351 case Type::IntegerTyID: {
352 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
353 return "IntegerType::get(" + utostr(BitWidth) + ")";
355 case Type::FloatTyID: return "Type::FloatTy";
356 case Type::DoubleTyID: return "Type::DoubleTy";
357 case Type::LabelTyID: return "Type::LabelTy";
359 error("Invalid primitive type");
362 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
365 // Now, see if we've seen the type before and return that
366 TypeMap::iterator I = TypeNames.find(Ty);
367 if (I != TypeNames.end())
370 // Okay, let's build a new name for this type. Start with a prefix
371 const char* prefix = 0;
372 switch (Ty->getTypeID()) {
373 case Type::FunctionTyID: prefix = "FuncTy_"; break;
374 case Type::StructTyID: prefix = "StructTy_"; break;
375 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
376 case Type::PointerTyID: prefix = "PointerTy_"; break;
377 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
378 case Type::VectorTyID: prefix = "VectorTy_"; break;
379 default: prefix = "OtherTy_"; break; // prevent breakage
382 // See if the type has a name in the symboltable and build accordingly
383 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
386 name = std::string(prefix) + *tName;
388 name = std::string(prefix) + utostr(uniqueNum++);
392 return TypeNames[Ty] = name;
395 void CppWriter::printCppName(const Type* Ty) {
396 printEscapedString(getCppName(Ty));
399 std::string CppWriter::getCppName(const Value* val) {
401 ValueMap::iterator I = ValueNames.find(val);
402 if (I != ValueNames.end() && I->first == val)
405 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
406 name = std::string("gvar_") +
407 getTypePrefix(GV->getType()->getElementType());
408 } else if (isa<Function>(val)) {
409 name = std::string("func_");
410 } else if (const Constant* C = dyn_cast<Constant>(val)) {
411 name = std::string("const_") + getTypePrefix(C->getType());
412 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
414 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
415 Function::const_arg_iterator(Arg)) + 1;
416 name = std::string("arg_") + utostr(argNum);
417 NameSet::iterator NI = UsedNames.find(name);
418 if (NI != UsedNames.end())
419 name += std::string("_") + utostr(uniqueNum++);
420 UsedNames.insert(name);
421 return ValueNames[val] = name;
423 name = getTypePrefix(val->getType());
426 name = getTypePrefix(val->getType());
428 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
430 NameSet::iterator NI = UsedNames.find(name);
431 if (NI != UsedNames.end())
432 name += std::string("_") + utostr(uniqueNum++);
433 UsedNames.insert(name);
434 return ValueNames[val] = name;
437 void CppWriter::printCppName(const Value* val) {
438 printEscapedString(getCppName(val));
441 void CppWriter::printAttributes(const AttrListPtr &PAL,
442 const std::string &name) {
443 Out << "AttrListPtr " << name << "_PAL;";
445 if (!PAL.isEmpty()) {
446 Out << '{'; in(); nl(Out);
447 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
448 Out << "AttributeWithIndex PAWI;"; nl(Out);
449 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
450 unsigned index = PAL.getSlot(i).Index;
451 Attributes attrs = PAL.getSlot(i).Attrs;
452 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
453 if (attrs & Attribute::SExt)
454 Out << " | Attribute::SExt";
455 if (attrs & Attribute::ZExt)
456 Out << " | Attribute::ZExt";
457 if (attrs & Attribute::StructRet)
458 Out << " | Attribute::StructRet";
459 if (attrs & Attribute::InReg)
460 Out << " | Attribute::InReg";
461 if (attrs & Attribute::NoReturn)
462 Out << " | Attribute::NoReturn";
463 if (attrs & Attribute::NoUnwind)
464 Out << " | Attribute::NoUnwind";
465 if (attrs & Attribute::ByVal)
466 Out << " | Attribute::ByVal";
467 if (attrs & Attribute::NoAlias)
468 Out << " | Attribute::NoAlias";
469 if (attrs & Attribute::Nest)
470 Out << " | Attribute::Nest";
471 if (attrs & Attribute::ReadNone)
472 Out << " | Attribute::ReadNone";
473 if (attrs & Attribute::ReadOnly)
474 Out << " | Attribute::ReadOnly";
477 Out << "Attrs.push_back(PAWI);";
480 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
487 bool CppWriter::printTypeInternal(const Type* Ty) {
488 // We don't print definitions for primitive types
489 if (Ty->isPrimitiveType() || Ty->isInteger())
492 // If we already defined this type, we don't need to define it again.
493 if (DefinedTypes.find(Ty) != DefinedTypes.end())
496 // Everything below needs the name for the type so get it now.
497 std::string typeName(getCppName(Ty));
499 // Search the type stack for recursion. If we find it, then generate this
500 // as an OpaqueType, but make sure not to do this multiple times because
501 // the type could appear in multiple places on the stack. Once the opaque
502 // definition is issued, it must not be re-issued. Consequently we have to
503 // check the UnresolvedTypes list as well.
504 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
506 if (TI != TypeStack.end()) {
507 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
508 if (I == UnresolvedTypes.end()) {
509 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
511 UnresolvedTypes[Ty] = typeName;
516 // We're going to print a derived type which, by definition, contains other
517 // types. So, push this one we're printing onto the type stack to assist with
518 // recursive definitions.
519 TypeStack.push_back(Ty);
521 // Print the type definition
522 switch (Ty->getTypeID()) {
523 case Type::FunctionTyID: {
524 const FunctionType* FT = cast<FunctionType>(Ty);
525 Out << "std::vector<const Type*>" << typeName << "_args;";
527 FunctionType::param_iterator PI = FT->param_begin();
528 FunctionType::param_iterator PE = FT->param_end();
529 for (; PI != PE; ++PI) {
530 const Type* argTy = static_cast<const Type*>(*PI);
531 bool isForward = printTypeInternal(argTy);
532 std::string argName(getCppName(argTy));
533 Out << typeName << "_args.push_back(" << argName;
539 bool isForward = printTypeInternal(FT->getReturnType());
540 std::string retTypeName(getCppName(FT->getReturnType()));
541 Out << "FunctionType* " << typeName << " = FunctionType::get(";
542 in(); nl(Out) << "/*Result=*/" << retTypeName;
546 nl(Out) << "/*Params=*/" << typeName << "_args,";
547 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
552 case Type::StructTyID: {
553 const StructType* ST = cast<StructType>(Ty);
554 Out << "std::vector<const Type*>" << typeName << "_fields;";
556 StructType::element_iterator EI = ST->element_begin();
557 StructType::element_iterator EE = ST->element_end();
558 for (; EI != EE; ++EI) {
559 const Type* fieldTy = static_cast<const Type*>(*EI);
560 bool isForward = printTypeInternal(fieldTy);
561 std::string fieldName(getCppName(fieldTy));
562 Out << typeName << "_fields.push_back(" << fieldName;
568 Out << "StructType* " << typeName << " = StructType::get("
569 << typeName << "_fields, /*isPacked=*/"
570 << (ST->isPacked() ? "true" : "false") << ");";
574 case Type::ArrayTyID: {
575 const ArrayType* AT = cast<ArrayType>(Ty);
576 const Type* ET = AT->getElementType();
577 bool isForward = printTypeInternal(ET);
578 std::string elemName(getCppName(ET));
579 Out << "ArrayType* " << typeName << " = ArrayType::get("
580 << elemName << (isForward ? "_fwd" : "")
581 << ", " << utostr(AT->getNumElements()) << ");";
585 case Type::PointerTyID: {
586 const PointerType* PT = cast<PointerType>(Ty);
587 const Type* ET = PT->getElementType();
588 bool isForward = printTypeInternal(ET);
589 std::string elemName(getCppName(ET));
590 Out << "PointerType* " << typeName << " = PointerType::get("
591 << elemName << (isForward ? "_fwd" : "")
592 << ", " << utostr(PT->getAddressSpace()) << ");";
596 case Type::VectorTyID: {
597 const VectorType* PT = cast<VectorType>(Ty);
598 const Type* ET = PT->getElementType();
599 bool isForward = printTypeInternal(ET);
600 std::string elemName(getCppName(ET));
601 Out << "VectorType* " << typeName << " = VectorType::get("
602 << elemName << (isForward ? "_fwd" : "")
603 << ", " << utostr(PT->getNumElements()) << ");";
607 case Type::OpaqueTyID: {
608 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
613 error("Invalid TypeID");
616 // If the type had a name, make sure we recreate it.
617 const std::string* progTypeName =
618 findTypeName(TheModule->getTypeSymbolTable(),Ty);
620 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
625 // Pop us off the type stack
626 TypeStack.pop_back();
628 // Indicate that this type is now defined.
629 DefinedTypes.insert(Ty);
631 // Early resolve as many unresolved types as possible. Search the unresolved
632 // types map for the type we just printed. Now that its definition is complete
633 // we can resolve any previous references to it. This prevents a cascade of
635 TypeMap::iterator I = UnresolvedTypes.find(Ty);
636 if (I != UnresolvedTypes.end()) {
637 Out << "cast<OpaqueType>(" << I->second
638 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
640 Out << I->second << " = cast<";
641 switch (Ty->getTypeID()) {
642 case Type::FunctionTyID: Out << "FunctionType"; break;
643 case Type::ArrayTyID: Out << "ArrayType"; break;
644 case Type::StructTyID: Out << "StructType"; break;
645 case Type::VectorTyID: Out << "VectorType"; break;
646 case Type::PointerTyID: Out << "PointerType"; break;
647 case Type::OpaqueTyID: Out << "OpaqueType"; break;
648 default: Out << "NoSuchDerivedType"; break;
650 Out << ">(" << I->second << "_fwd.get());";
652 UnresolvedTypes.erase(I);
655 // Finally, separate the type definition from other with a newline.
658 // We weren't a recursive type
662 // Prints a type definition. Returns true if it could not resolve all the
663 // types in the definition but had to use a forward reference.
664 void CppWriter::printType(const Type* Ty) {
665 assert(TypeStack.empty());
667 printTypeInternal(Ty);
668 assert(TypeStack.empty());
671 void CppWriter::printTypes(const Module* M) {
672 // Walk the symbol table and print out all its types
673 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
674 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
677 // For primitive types and types already defined, just add a name
678 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
679 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
680 TNI != TypeNames.end()) {
681 Out << "mod->addTypeName(\"";
682 printEscapedString(TI->first);
683 Out << "\", " << getCppName(TI->second) << ");";
685 // For everything else, define the type
687 printType(TI->second);
691 // Add all of the global variables to the value table...
692 for (Module::const_global_iterator I = TheModule->global_begin(),
693 E = TheModule->global_end(); I != E; ++I) {
694 if (I->hasInitializer())
695 printType(I->getInitializer()->getType());
696 printType(I->getType());
699 // Add all the functions to the table
700 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
702 printType(FI->getReturnType());
703 printType(FI->getFunctionType());
704 // Add all the function arguments
705 for (Function::const_arg_iterator AI = FI->arg_begin(),
706 AE = FI->arg_end(); AI != AE; ++AI) {
707 printType(AI->getType());
710 // Add all of the basic blocks and instructions
711 for (Function::const_iterator BB = FI->begin(),
712 E = FI->end(); BB != E; ++BB) {
713 printType(BB->getType());
714 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
716 printType(I->getType());
717 for (unsigned i = 0; i < I->getNumOperands(); ++i)
718 printType(I->getOperand(i)->getType());
725 // printConstant - Print out a constant pool entry...
726 void CppWriter::printConstant(const Constant *CV) {
727 // First, if the constant is actually a GlobalValue (variable or function)
728 // or its already in the constant list then we've printed it already and we
730 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
733 std::string constName(getCppName(CV));
734 std::string typeName(getCppName(CV->getType()));
736 if (isa<GlobalValue>(CV)) {
737 // Skip variables and functions, we emit them elsewhere
741 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
742 std::string constValue = CI->getValue().toString(10, true);
743 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
744 << cast<IntegerType>(CI->getType())->getBitWidth() << ", \""
745 << constValue << "\", " << constValue.length() << ", 10));";
746 } else if (isa<ConstantAggregateZero>(CV)) {
747 Out << "ConstantAggregateZero* " << constName
748 << " = ConstantAggregateZero::get(" << typeName << ");";
749 } else if (isa<ConstantPointerNull>(CV)) {
750 Out << "ConstantPointerNull* " << constName
751 << " = ConstantPointerNull::get(" << typeName << ");";
752 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
753 Out << "ConstantFP* " << constName << " = ";
756 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
757 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
758 Out << "Constant* " << constName << " = ConstantArray::get(\"";
759 std::string tmp = CA->getAsString();
760 bool nullTerminate = false;
761 if (tmp[tmp.length()-1] == 0) {
762 tmp.erase(tmp.length()-1);
763 nullTerminate = true;
765 printEscapedString(tmp);
766 // Determine if we want null termination or not.
768 Out << "\", true"; // Indicate that the null terminator should be
771 Out << "\", false";// No null terminator
774 Out << "std::vector<Constant*> " << constName << "_elems;";
776 unsigned N = CA->getNumOperands();
777 for (unsigned i = 0; i < N; ++i) {
778 printConstant(CA->getOperand(i)); // recurse to print operands
779 Out << constName << "_elems.push_back("
780 << getCppName(CA->getOperand(i)) << ");";
783 Out << "Constant* " << constName << " = ConstantArray::get("
784 << typeName << ", " << constName << "_elems);";
786 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
787 Out << "std::vector<Constant*> " << constName << "_fields;";
789 unsigned N = CS->getNumOperands();
790 for (unsigned i = 0; i < N; i++) {
791 printConstant(CS->getOperand(i));
792 Out << constName << "_fields.push_back("
793 << getCppName(CS->getOperand(i)) << ");";
796 Out << "Constant* " << constName << " = ConstantStruct::get("
797 << typeName << ", " << constName << "_fields);";
798 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
799 Out << "std::vector<Constant*> " << constName << "_elems;";
801 unsigned N = CP->getNumOperands();
802 for (unsigned i = 0; i < N; ++i) {
803 printConstant(CP->getOperand(i));
804 Out << constName << "_elems.push_back("
805 << getCppName(CP->getOperand(i)) << ");";
808 Out << "Constant* " << constName << " = ConstantVector::get("
809 << typeName << ", " << constName << "_elems);";
810 } else if (isa<UndefValue>(CV)) {
811 Out << "UndefValue* " << constName << " = UndefValue::get("
813 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
814 if (CE->getOpcode() == Instruction::GetElementPtr) {
815 Out << "std::vector<Constant*> " << constName << "_indices;";
817 printConstant(CE->getOperand(0));
818 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
819 printConstant(CE->getOperand(i));
820 Out << constName << "_indices.push_back("
821 << getCppName(CE->getOperand(i)) << ");";
824 Out << "Constant* " << constName
825 << " = ConstantExpr::getGetElementPtr("
826 << getCppName(CE->getOperand(0)) << ", "
827 << "&" << constName << "_indices[0], "
828 << constName << "_indices.size()"
830 } else if (CE->isCast()) {
831 printConstant(CE->getOperand(0));
832 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
833 switch (CE->getOpcode()) {
834 default: assert(0 && "Invalid cast opcode");
835 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
836 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
837 case Instruction::SExt: Out << "Instruction::SExt"; break;
838 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
839 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
840 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
841 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
842 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
843 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
844 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
845 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
846 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
848 Out << ", " << getCppName(CE->getOperand(0)) << ", "
849 << getCppName(CE->getType()) << ");";
851 unsigned N = CE->getNumOperands();
852 for (unsigned i = 0; i < N; ++i ) {
853 printConstant(CE->getOperand(i));
855 Out << "Constant* " << constName << " = ConstantExpr::";
856 switch (CE->getOpcode()) {
857 case Instruction::Add: Out << "getAdd("; break;
858 case Instruction::Sub: Out << "getSub("; break;
859 case Instruction::Mul: Out << "getMul("; break;
860 case Instruction::UDiv: Out << "getUDiv("; break;
861 case Instruction::SDiv: Out << "getSDiv("; break;
862 case Instruction::FDiv: Out << "getFDiv("; break;
863 case Instruction::URem: Out << "getURem("; break;
864 case Instruction::SRem: Out << "getSRem("; break;
865 case Instruction::FRem: Out << "getFRem("; break;
866 case Instruction::And: Out << "getAnd("; break;
867 case Instruction::Or: Out << "getOr("; break;
868 case Instruction::Xor: Out << "getXor("; break;
869 case Instruction::ICmp:
870 Out << "getICmp(ICmpInst::ICMP_";
871 switch (CE->getPredicate()) {
872 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
873 case ICmpInst::ICMP_NE: Out << "NE"; break;
874 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
875 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
876 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
877 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
878 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
879 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
880 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
881 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
882 default: error("Invalid ICmp Predicate");
885 case Instruction::FCmp:
886 Out << "getFCmp(FCmpInst::FCMP_";
887 switch (CE->getPredicate()) {
888 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
889 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
890 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
891 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
892 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
893 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
894 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
895 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
896 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
897 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
898 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
899 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
900 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
901 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
902 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
903 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
904 default: error("Invalid FCmp Predicate");
907 case Instruction::Shl: Out << "getShl("; break;
908 case Instruction::LShr: Out << "getLShr("; break;
909 case Instruction::AShr: Out << "getAShr("; break;
910 case Instruction::Select: Out << "getSelect("; break;
911 case Instruction::ExtractElement: Out << "getExtractElement("; break;
912 case Instruction::InsertElement: Out << "getInsertElement("; break;
913 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
915 error("Invalid constant expression");
918 Out << getCppName(CE->getOperand(0));
919 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
920 Out << ", " << getCppName(CE->getOperand(i));
924 error("Bad Constant");
925 Out << "Constant* " << constName << " = 0; ";
930 void CppWriter::printConstants(const Module* M) {
931 // Traverse all the global variables looking for constant initializers
932 for (Module::const_global_iterator I = TheModule->global_begin(),
933 E = TheModule->global_end(); I != E; ++I)
934 if (I->hasInitializer())
935 printConstant(I->getInitializer());
937 // Traverse the LLVM functions looking for constants
938 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
940 // Add all of the basic blocks and instructions
941 for (Function::const_iterator BB = FI->begin(),
942 E = FI->end(); BB != E; ++BB) {
943 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
945 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
946 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
955 void CppWriter::printVariableUses(const GlobalVariable *GV) {
956 nl(Out) << "// Type Definitions";
958 printType(GV->getType());
959 if (GV->hasInitializer()) {
960 Constant* Init = GV->getInitializer();
961 printType(Init->getType());
962 if (Function* F = dyn_cast<Function>(Init)) {
963 nl(Out)<< "/ Function Declarations"; nl(Out);
964 printFunctionHead(F);
965 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
966 nl(Out) << "// Global Variable Declarations"; nl(Out);
967 printVariableHead(gv);
969 nl(Out) << "// Constant Definitions"; nl(Out);
972 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
973 nl(Out) << "// Global Variable Definitions"; nl(Out);
974 printVariableBody(gv);
979 void CppWriter::printVariableHead(const GlobalVariable *GV) {
980 nl(Out) << "GlobalVariable* " << getCppName(GV);
982 Out << " = mod->getGlobalVariable(";
983 printEscapedString(GV->getName());
984 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
985 nl(Out) << "if (!" << getCppName(GV) << ") {";
986 in(); nl(Out) << getCppName(GV);
988 Out << " = new GlobalVariable(";
989 nl(Out) << "/*Type=*/";
990 printCppName(GV->getType()->getElementType());
992 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
994 nl(Out) << "/*Linkage=*/";
995 printLinkageType(GV->getLinkage());
997 nl(Out) << "/*Initializer=*/0, ";
998 if (GV->hasInitializer()) {
999 Out << "// has initializer, specified below";
1001 nl(Out) << "/*Name=*/\"";
1002 printEscapedString(GV->getName());
1007 if (GV->hasSection()) {
1009 Out << "->setSection(\"";
1010 printEscapedString(GV->getSection());
1014 if (GV->getAlignment()) {
1016 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1019 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1021 Out << "->setVisibility(";
1022 printVisibilityType(GV->getVisibility());
1027 out(); Out << "}"; nl(Out);
1031 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1032 if (GV->hasInitializer()) {
1034 Out << "->setInitializer(";
1035 Out << getCppName(GV->getInitializer()) << ");";
1040 std::string CppWriter::getOpName(Value* V) {
1041 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1042 return getCppName(V);
1044 // See if its alread in the map of forward references, if so just return the
1045 // name we already set up for it
1046 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1047 if (I != ForwardRefs.end())
1050 // This is a new forward reference. Generate a unique name for it
1051 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1053 // Yes, this is a hack. An Argument is the smallest instantiable value that
1054 // we can make as a placeholder for the real value. We'll replace these
1055 // Argument instances later.
1056 Out << "Argument* " << result << " = new Argument("
1057 << getCppName(V->getType()) << ");";
1059 ForwardRefs[V] = result;
1063 // printInstruction - This member is called for each Instruction in a function.
1064 void CppWriter::printInstruction(const Instruction *I,
1065 const std::string& bbname) {
1066 std::string iName(getCppName(I));
1068 // Before we emit this instruction, we need to take care of generating any
1069 // forward references. So, we get the names of all the operands in advance
1070 std::string* opNames = new std::string[I->getNumOperands()];
1071 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1072 opNames[i] = getOpName(I->getOperand(i));
1075 switch (I->getOpcode()) {
1077 error("Invalid instruction");
1080 case Instruction::Ret: {
1081 const ReturnInst* ret = cast<ReturnInst>(I);
1082 Out << "ReturnInst::Create("
1083 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1086 case Instruction::Br: {
1087 const BranchInst* br = cast<BranchInst>(I);
1088 Out << "BranchInst::Create(" ;
1089 if (br->getNumOperands() == 3 ) {
1090 Out << opNames[0] << ", "
1091 << opNames[1] << ", "
1092 << opNames[2] << ", ";
1094 } else if (br->getNumOperands() == 1) {
1095 Out << opNames[0] << ", ";
1097 error("Branch with 2 operands?");
1099 Out << bbname << ");";
1102 case Instruction::Switch: {
1103 const SwitchInst* sw = cast<SwitchInst>(I);
1104 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1105 << opNames[0] << ", "
1106 << opNames[1] << ", "
1107 << sw->getNumCases() << ", " << bbname << ");";
1109 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1110 Out << iName << "->addCase("
1111 << opNames[i] << ", "
1112 << opNames[i+1] << ");";
1117 case Instruction::Invoke: {
1118 const InvokeInst* inv = cast<InvokeInst>(I);
1119 Out << "std::vector<Value*> " << iName << "_params;";
1121 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1122 Out << iName << "_params.push_back("
1123 << opNames[i] << ");";
1126 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1127 << opNames[0] << ", "
1128 << opNames[1] << ", "
1129 << opNames[2] << ", "
1130 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1131 printEscapedString(inv->getName());
1132 Out << "\", " << bbname << ");";
1133 nl(Out) << iName << "->setCallingConv(";
1134 printCallingConv(inv->getCallingConv());
1136 printAttributes(inv->getAttributes(), iName);
1137 Out << iName << "->setAttributes(" << iName << "_PAL);";
1141 case Instruction::Unwind: {
1142 Out << "new UnwindInst("
1146 case Instruction::Unreachable:{
1147 Out << "new UnreachableInst("
1151 case Instruction::Add:
1152 case Instruction::Sub:
1153 case Instruction::Mul:
1154 case Instruction::UDiv:
1155 case Instruction::SDiv:
1156 case Instruction::FDiv:
1157 case Instruction::URem:
1158 case Instruction::SRem:
1159 case Instruction::FRem:
1160 case Instruction::And:
1161 case Instruction::Or:
1162 case Instruction::Xor:
1163 case Instruction::Shl:
1164 case Instruction::LShr:
1165 case Instruction::AShr:{
1166 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1167 switch (I->getOpcode()) {
1168 case Instruction::Add: Out << "Instruction::Add"; break;
1169 case Instruction::Sub: Out << "Instruction::Sub"; break;
1170 case Instruction::Mul: Out << "Instruction::Mul"; break;
1171 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1172 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1173 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1174 case Instruction::URem:Out << "Instruction::URem"; break;
1175 case Instruction::SRem:Out << "Instruction::SRem"; break;
1176 case Instruction::FRem:Out << "Instruction::FRem"; break;
1177 case Instruction::And: Out << "Instruction::And"; break;
1178 case Instruction::Or: Out << "Instruction::Or"; break;
1179 case Instruction::Xor: Out << "Instruction::Xor"; break;
1180 case Instruction::Shl: Out << "Instruction::Shl"; break;
1181 case Instruction::LShr:Out << "Instruction::LShr"; break;
1182 case Instruction::AShr:Out << "Instruction::AShr"; break;
1183 default: Out << "Instruction::BadOpCode"; break;
1185 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1186 printEscapedString(I->getName());
1187 Out << "\", " << bbname << ");";
1190 case Instruction::FCmp: {
1191 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1192 switch (cast<FCmpInst>(I)->getPredicate()) {
1193 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1194 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1195 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1196 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1197 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1198 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1199 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1200 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1201 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1202 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1203 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1204 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1205 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1206 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1207 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1208 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1209 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1211 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1212 printEscapedString(I->getName());
1213 Out << "\", " << bbname << ");";
1216 case Instruction::ICmp: {
1217 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1218 switch (cast<ICmpInst>(I)->getPredicate()) {
1219 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1220 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1221 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1222 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1223 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1224 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1225 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1226 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1227 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1228 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1229 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1231 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1232 printEscapedString(I->getName());
1233 Out << "\", " << bbname << ");";
1236 case Instruction::Malloc: {
1237 const MallocInst* mallocI = cast<MallocInst>(I);
1238 Out << "MallocInst* " << iName << " = new MallocInst("
1239 << getCppName(mallocI->getAllocatedType()) << ", ";
1240 if (mallocI->isArrayAllocation())
1241 Out << opNames[0] << ", " ;
1243 printEscapedString(mallocI->getName());
1244 Out << "\", " << bbname << ");";
1245 if (mallocI->getAlignment())
1246 nl(Out) << iName << "->setAlignment("
1247 << mallocI->getAlignment() << ");";
1250 case Instruction::Free: {
1251 Out << "FreeInst* " << iName << " = new FreeInst("
1252 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1255 case Instruction::Alloca: {
1256 const AllocaInst* allocaI = cast<AllocaInst>(I);
1257 Out << "AllocaInst* " << iName << " = new AllocaInst("
1258 << getCppName(allocaI->getAllocatedType()) << ", ";
1259 if (allocaI->isArrayAllocation())
1260 Out << opNames[0] << ", ";
1262 printEscapedString(allocaI->getName());
1263 Out << "\", " << bbname << ");";
1264 if (allocaI->getAlignment())
1265 nl(Out) << iName << "->setAlignment("
1266 << allocaI->getAlignment() << ");";
1269 case Instruction::Load:{
1270 const LoadInst* load = cast<LoadInst>(I);
1271 Out << "LoadInst* " << iName << " = new LoadInst("
1272 << opNames[0] << ", \"";
1273 printEscapedString(load->getName());
1274 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1275 << ", " << bbname << ");";
1278 case Instruction::Store: {
1279 const StoreInst* store = cast<StoreInst>(I);
1280 Out << " new StoreInst("
1281 << opNames[0] << ", "
1282 << opNames[1] << ", "
1283 << (store->isVolatile() ? "true" : "false")
1284 << ", " << bbname << ");";
1287 case Instruction::GetElementPtr: {
1288 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1289 if (gep->getNumOperands() <= 2) {
1290 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1292 if (gep->getNumOperands() == 2)
1293 Out << ", " << opNames[1];
1295 Out << "std::vector<Value*> " << iName << "_indices;";
1297 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1298 Out << iName << "_indices.push_back("
1299 << opNames[i] << ");";
1302 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1303 << opNames[0] << ", " << iName << "_indices.begin(), "
1304 << iName << "_indices.end()";
1307 printEscapedString(gep->getName());
1308 Out << "\", " << bbname << ");";
1311 case Instruction::PHI: {
1312 const PHINode* phi = cast<PHINode>(I);
1314 Out << "PHINode* " << iName << " = PHINode::Create("
1315 << getCppName(phi->getType()) << ", \"";
1316 printEscapedString(phi->getName());
1317 Out << "\", " << bbname << ");";
1318 nl(Out) << iName << "->reserveOperandSpace("
1319 << phi->getNumIncomingValues()
1322 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1323 Out << iName << "->addIncoming("
1324 << opNames[i] << ", " << opNames[i+1] << ");";
1329 case Instruction::Trunc:
1330 case Instruction::ZExt:
1331 case Instruction::SExt:
1332 case Instruction::FPTrunc:
1333 case Instruction::FPExt:
1334 case Instruction::FPToUI:
1335 case Instruction::FPToSI:
1336 case Instruction::UIToFP:
1337 case Instruction::SIToFP:
1338 case Instruction::PtrToInt:
1339 case Instruction::IntToPtr:
1340 case Instruction::BitCast: {
1341 const CastInst* cst = cast<CastInst>(I);
1342 Out << "CastInst* " << iName << " = new ";
1343 switch (I->getOpcode()) {
1344 case Instruction::Trunc: Out << "TruncInst"; break;
1345 case Instruction::ZExt: Out << "ZExtInst"; break;
1346 case Instruction::SExt: Out << "SExtInst"; break;
1347 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1348 case Instruction::FPExt: Out << "FPExtInst"; break;
1349 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1350 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1351 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1352 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1353 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1354 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1355 case Instruction::BitCast: Out << "BitCastInst"; break;
1356 default: assert(!"Unreachable"); break;
1358 Out << "(" << opNames[0] << ", "
1359 << getCppName(cst->getType()) << ", \"";
1360 printEscapedString(cst->getName());
1361 Out << "\", " << bbname << ");";
1364 case Instruction::Call:{
1365 const CallInst* call = cast<CallInst>(I);
1366 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1367 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1368 << getCppName(ila->getFunctionType()) << ", \""
1369 << ila->getAsmString() << "\", \""
1370 << ila->getConstraintString() << "\","
1371 << (ila->hasSideEffects() ? "true" : "false") << ");";
1374 if (call->getNumOperands() > 2) {
1375 Out << "std::vector<Value*> " << iName << "_params;";
1377 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1378 Out << iName << "_params.push_back(" << opNames[i] << ");";
1381 Out << "CallInst* " << iName << " = CallInst::Create("
1382 << opNames[0] << ", " << iName << "_params.begin(), "
1383 << iName << "_params.end(), \"";
1384 } else if (call->getNumOperands() == 2) {
1385 Out << "CallInst* " << iName << " = CallInst::Create("
1386 << opNames[0] << ", " << opNames[1] << ", \"";
1388 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1391 printEscapedString(call->getName());
1392 Out << "\", " << bbname << ");";
1393 nl(Out) << iName << "->setCallingConv(";
1394 printCallingConv(call->getCallingConv());
1396 nl(Out) << iName << "->setTailCall("
1397 << (call->isTailCall() ? "true":"false");
1399 printAttributes(call->getAttributes(), iName);
1400 Out << iName << "->setAttributes(" << iName << "_PAL);";
1404 case Instruction::Select: {
1405 const SelectInst* sel = cast<SelectInst>(I);
1406 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1407 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1408 printEscapedString(sel->getName());
1409 Out << "\", " << bbname << ");";
1412 case Instruction::UserOp1:
1414 case Instruction::UserOp2: {
1415 /// FIXME: What should be done here?
1418 case Instruction::VAArg: {
1419 const VAArgInst* va = cast<VAArgInst>(I);
1420 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1421 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1422 printEscapedString(va->getName());
1423 Out << "\", " << bbname << ");";
1426 case Instruction::ExtractElement: {
1427 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1428 Out << "ExtractElementInst* " << getCppName(eei)
1429 << " = new ExtractElementInst(" << opNames[0]
1430 << ", " << opNames[1] << ", \"";
1431 printEscapedString(eei->getName());
1432 Out << "\", " << bbname << ");";
1435 case Instruction::InsertElement: {
1436 const InsertElementInst* iei = cast<InsertElementInst>(I);
1437 Out << "InsertElementInst* " << getCppName(iei)
1438 << " = InsertElementInst::Create(" << opNames[0]
1439 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1440 printEscapedString(iei->getName());
1441 Out << "\", " << bbname << ");";
1444 case Instruction::ShuffleVector: {
1445 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1446 Out << "ShuffleVectorInst* " << getCppName(svi)
1447 << " = new ShuffleVectorInst(" << opNames[0]
1448 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1449 printEscapedString(svi->getName());
1450 Out << "\", " << bbname << ");";
1453 case Instruction::ExtractValue: {
1454 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1455 Out << "std::vector<unsigned> " << iName << "_indices;";
1457 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1458 Out << iName << "_indices.push_back("
1459 << evi->idx_begin()[i] << ");";
1462 Out << "ExtractValueInst* " << getCppName(evi)
1463 << " = ExtractValueInst::Create(" << opNames[0]
1465 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1466 printEscapedString(evi->getName());
1467 Out << "\", " << bbname << ");";
1470 case Instruction::InsertValue: {
1471 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1472 Out << "std::vector<unsigned> " << iName << "_indices;";
1474 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1475 Out << iName << "_indices.push_back("
1476 << ivi->idx_begin()[i] << ");";
1479 Out << "InsertValueInst* " << getCppName(ivi)
1480 << " = InsertValueInst::Create(" << opNames[0]
1481 << ", " << opNames[1] << ", "
1482 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1483 printEscapedString(ivi->getName());
1484 Out << "\", " << bbname << ");";
1488 DefinedValues.insert(I);
1493 // Print out the types, constants and declarations needed by one function
1494 void CppWriter::printFunctionUses(const Function* F) {
1495 nl(Out) << "// Type Definitions"; nl(Out);
1497 // Print the function's return type
1498 printType(F->getReturnType());
1500 // Print the function's function type
1501 printType(F->getFunctionType());
1503 // Print the types of each of the function's arguments
1504 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1506 printType(AI->getType());
1510 // Print type definitions for every type referenced by an instruction and
1511 // make a note of any global values or constants that are referenced
1512 SmallPtrSet<GlobalValue*,64> gvs;
1513 SmallPtrSet<Constant*,64> consts;
1514 for (Function::const_iterator BB = F->begin(), BE = F->end();
1516 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1518 // Print the type of the instruction itself
1519 printType(I->getType());
1521 // Print the type of each of the instruction's operands
1522 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1523 Value* operand = I->getOperand(i);
1524 printType(operand->getType());
1526 // If the operand references a GVal or Constant, make a note of it
1527 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1529 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1530 if (GVar->hasInitializer())
1531 consts.insert(GVar->getInitializer());
1532 } else if (Constant* C = dyn_cast<Constant>(operand))
1538 // Print the function declarations for any functions encountered
1539 nl(Out) << "// Function Declarations"; nl(Out);
1540 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1542 if (Function* Fun = dyn_cast<Function>(*I)) {
1543 if (!is_inline || Fun != F)
1544 printFunctionHead(Fun);
1548 // Print the global variable declarations for any variables encountered
1549 nl(Out) << "// Global Variable Declarations"; nl(Out);
1550 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1552 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1553 printVariableHead(F);
1556 // Print the constants found
1557 nl(Out) << "// Constant Definitions"; nl(Out);
1558 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1559 E = consts.end(); I != E; ++I) {
1563 // Process the global variables definitions now that all the constants have
1564 // been emitted. These definitions just couple the gvars with their constant
1566 nl(Out) << "// Global Variable Definitions"; nl(Out);
1567 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1569 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1570 printVariableBody(GV);
1574 void CppWriter::printFunctionHead(const Function* F) {
1575 nl(Out) << "Function* " << getCppName(F);
1577 Out << " = mod->getFunction(\"";
1578 printEscapedString(F->getName());
1579 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1580 nl(Out) << "if (!" << getCppName(F) << ") {";
1581 nl(Out) << getCppName(F);
1583 Out<< " = Function::Create(";
1584 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1585 nl(Out) << "/*Linkage=*/";
1586 printLinkageType(F->getLinkage());
1588 nl(Out) << "/*Name=*/\"";
1589 printEscapedString(F->getName());
1590 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1593 Out << "->setCallingConv(";
1594 printCallingConv(F->getCallingConv());
1597 if (F->hasSection()) {
1599 Out << "->setSection(\"" << F->getSection() << "\");";
1602 if (F->getAlignment()) {
1604 Out << "->setAlignment(" << F->getAlignment() << ");";
1607 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1609 Out << "->setVisibility(";
1610 printVisibilityType(F->getVisibility());
1616 Out << "->setGC(\"" << F->getGC() << "\");";
1623 printAttributes(F->getAttributes(), getCppName(F));
1625 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1629 void CppWriter::printFunctionBody(const Function *F) {
1630 if (F->isDeclaration())
1631 return; // external functions have no bodies.
1633 // Clear the DefinedValues and ForwardRefs maps because we can't have
1634 // cross-function forward refs
1635 ForwardRefs.clear();
1636 DefinedValues.clear();
1638 // Create all the argument values
1640 if (!F->arg_empty()) {
1641 Out << "Function::arg_iterator args = " << getCppName(F)
1642 << "->arg_begin();";
1645 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1647 Out << "Value* " << getCppName(AI) << " = args++;";
1649 if (AI->hasName()) {
1650 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1656 // Create all the basic blocks
1658 for (Function::const_iterator BI = F->begin(), BE = F->end();
1660 std::string bbname(getCppName(BI));
1661 Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1663 printEscapedString(BI->getName());
1664 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1668 // Output all of its basic blocks... for the function
1669 for (Function::const_iterator BI = F->begin(), BE = F->end();
1671 std::string bbname(getCppName(BI));
1672 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1675 // Output all of the instructions in the basic block...
1676 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1678 printInstruction(I,bbname);
1682 // Loop over the ForwardRefs and resolve them now that all instructions
1684 if (!ForwardRefs.empty()) {
1685 nl(Out) << "// Resolve Forward References";
1689 while (!ForwardRefs.empty()) {
1690 ForwardRefMap::iterator I = ForwardRefs.begin();
1691 Out << I->second << "->replaceAllUsesWith("
1692 << getCppName(I->first) << "); delete " << I->second << ";";
1694 ForwardRefs.erase(I);
1698 void CppWriter::printInline(const std::string& fname,
1699 const std::string& func) {
1700 const Function* F = TheModule->getFunction(func);
1702 error(std::string("Function '") + func + "' not found in input module");
1705 if (F->isDeclaration()) {
1706 error(std::string("Function '") + func + "' is external!");
1709 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1711 unsigned arg_count = 1;
1712 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1714 Out << ", Value* arg_" << arg_count;
1719 printFunctionUses(F);
1720 printFunctionBody(F);
1722 Out << "return " << getCppName(F->begin()) << ";";
1727 void CppWriter::printModuleBody() {
1728 // Print out all the type definitions
1729 nl(Out) << "// Type Definitions"; nl(Out);
1730 printTypes(TheModule);
1732 // Functions can call each other and global variables can reference them so
1733 // define all the functions first before emitting their function bodies.
1734 nl(Out) << "// Function Declarations"; nl(Out);
1735 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1737 printFunctionHead(I);
1739 // Process the global variables declarations. We can't initialze them until
1740 // after the constants are printed so just print a header for each global
1741 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1742 for (Module::const_global_iterator I = TheModule->global_begin(),
1743 E = TheModule->global_end(); I != E; ++I) {
1744 printVariableHead(I);
1747 // Print out all the constants definitions. Constants don't recurse except
1748 // through GlobalValues. All GlobalValues have been declared at this point
1749 // so we can proceed to generate the constants.
1750 nl(Out) << "// Constant Definitions"; nl(Out);
1751 printConstants(TheModule);
1753 // Process the global variables definitions now that all the constants have
1754 // been emitted. These definitions just couple the gvars with their constant
1756 nl(Out) << "// Global Variable Definitions"; nl(Out);
1757 for (Module::const_global_iterator I = TheModule->global_begin(),
1758 E = TheModule->global_end(); I != E; ++I) {
1759 printVariableBody(I);
1762 // Finally, we can safely put out all of the function bodies.
1763 nl(Out) << "// Function Definitions"; nl(Out);
1764 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1766 if (!I->isDeclaration()) {
1767 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1771 printFunctionBody(I);
1778 void CppWriter::printProgram(const std::string& fname,
1779 const std::string& mName) {
1780 Out << "#include <llvm/Module.h>\n";
1781 Out << "#include <llvm/DerivedTypes.h>\n";
1782 Out << "#include <llvm/Constants.h>\n";
1783 Out << "#include <llvm/GlobalVariable.h>\n";
1784 Out << "#include <llvm/Function.h>\n";
1785 Out << "#include <llvm/CallingConv.h>\n";
1786 Out << "#include <llvm/BasicBlock.h>\n";
1787 Out << "#include <llvm/Instructions.h>\n";
1788 Out << "#include <llvm/InlineAsm.h>\n";
1789 Out << "#include <llvm/Support/MathExtras.h>\n";
1790 Out << "#include <llvm/Support/raw_ostream.h>\n";
1791 Out << "#include <llvm/Pass.h>\n";
1792 Out << "#include <llvm/PassManager.h>\n";
1793 Out << "#include <llvm/ADT/SmallVector.h>\n";
1794 Out << "#include <llvm/Analysis/Verifier.h>\n";
1795 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1796 Out << "#include <algorithm>\n";
1797 Out << "using namespace llvm;\n\n";
1798 Out << "Module* " << fname << "();\n\n";
1799 Out << "int main(int argc, char**argv) {\n";
1800 Out << " Module* Mod = " << fname << "();\n";
1801 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1802 Out << " errs().flush();\n";
1803 Out << " outs().flush();\n";
1804 Out << " PassManager PM;\n";
1805 Out << " PM.add(createPrintModulePass(&outs()));\n";
1806 Out << " PM.run(*Mod);\n";
1807 Out << " return 0;\n";
1809 printModule(fname,mName);
1812 void CppWriter::printModule(const std::string& fname,
1813 const std::string& mName) {
1814 nl(Out) << "Module* " << fname << "() {";
1815 nl(Out,1) << "// Module Construction";
1816 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1817 if (!TheModule->getTargetTriple().empty()) {
1818 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1820 if (!TheModule->getTargetTriple().empty()) {
1821 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1825 if (!TheModule->getModuleInlineAsm().empty()) {
1826 nl(Out) << "mod->setModuleInlineAsm(\"";
1827 printEscapedString(TheModule->getModuleInlineAsm());
1832 // Loop over the dependent libraries and emit them.
1833 Module::lib_iterator LI = TheModule->lib_begin();
1834 Module::lib_iterator LE = TheModule->lib_end();
1836 Out << "mod->addLibrary(\"" << *LI << "\");";
1841 nl(Out) << "return mod;";
1846 void CppWriter::printContents(const std::string& fname,
1847 const std::string& mName) {
1848 Out << "\nModule* " << fname << "(Module *mod) {\n";
1849 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1851 Out << "\nreturn mod;\n";
1855 void CppWriter::printFunction(const std::string& fname,
1856 const std::string& funcName) {
1857 const Function* F = TheModule->getFunction(funcName);
1859 error(std::string("Function '") + funcName + "' not found in input module");
1862 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1863 printFunctionUses(F);
1864 printFunctionHead(F);
1865 printFunctionBody(F);
1866 Out << "return " << getCppName(F) << ";\n";
1870 void CppWriter::printFunctions() {
1871 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1872 Module::const_iterator I = funcs.begin();
1873 Module::const_iterator IE = funcs.end();
1875 for (; I != IE; ++I) {
1876 const Function &func = *I;
1877 if (!func.isDeclaration()) {
1878 std::string name("define_");
1879 name += func.getName();
1880 printFunction(name, func.getName());
1885 void CppWriter::printVariable(const std::string& fname,
1886 const std::string& varName) {
1887 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1890 error(std::string("Variable '") + varName + "' not found in input module");
1893 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1894 printVariableUses(GV);
1895 printVariableHead(GV);
1896 printVariableBody(GV);
1897 Out << "return " << getCppName(GV) << ";\n";
1901 void CppWriter::printType(const std::string& fname,
1902 const std::string& typeName) {
1903 const Type* Ty = TheModule->getTypeByName(typeName);
1905 error(std::string("Type '") + typeName + "' not found in input module");
1908 Out << "\nType* " << fname << "(Module *mod) {\n";
1910 Out << "return " << getCppName(Ty) << ";\n";
1914 bool CppWriter::runOnModule(Module &M) {
1918 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1920 // Get the name of the function we're supposed to generate
1921 std::string fname = FuncName.getValue();
1923 // Get the name of the thing we are to generate
1924 std::string tgtname = NameToGenerate.getValue();
1925 if (GenerationType == GenModule ||
1926 GenerationType == GenContents ||
1927 GenerationType == GenProgram ||
1928 GenerationType == GenFunctions) {
1929 if (tgtname == "!bad!") {
1930 if (M.getModuleIdentifier() == "-")
1931 tgtname = "<stdin>";
1933 tgtname = M.getModuleIdentifier();
1935 } else if (tgtname == "!bad!")
1936 error("You must use the -for option with -gen-{function,variable,type}");
1938 switch (WhatToGenerate(GenerationType)) {
1941 fname = "makeLLVMModule";
1942 printProgram(fname,tgtname);
1946 fname = "makeLLVMModule";
1947 printModule(fname,tgtname);
1951 fname = "makeLLVMModuleContents";
1952 printContents(fname,tgtname);
1956 fname = "makeLLVMFunction";
1957 printFunction(fname,tgtname);
1964 fname = "makeLLVMInline";
1965 printInline(fname,tgtname);
1969 fname = "makeLLVMVariable";
1970 printVariable(fname,tgtname);
1974 fname = "makeLLVMType";
1975 printType(fname,tgtname);
1978 error("Invalid generation option");
1985 char CppWriter::ID = 0;
1987 //===----------------------------------------------------------------------===//
1988 // External Interface declaration
1989 //===----------------------------------------------------------------------===//
1991 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
1993 CodeGenFileType FileType,
1995 if (FileType != TargetMachine::AssemblyFile) return true;
1996 PM.add(new CppWriter(o));