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/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 // Register the target.
74 static RegisterTarget<CPPTargetMachine> X("cpp", " C++ backend");
77 typedef std::vector<const Type*> TypeList;
78 typedef std::map<const Type*,std::string> TypeMap;
79 typedef std::map<const Value*,std::string> ValueMap;
80 typedef std::set<std::string> NameSet;
81 typedef std::set<const Type*> TypeSet;
82 typedef std::set<const Value*> ValueSet;
83 typedef std::map<const Value*,std::string> ForwardRefMap;
85 /// CppWriter - This class is the main chunk of code that converts an LLVM
86 /// module to a C++ translation unit.
87 class CppWriter : public ModulePass {
90 const Module *TheModule;
94 TypeMap UnresolvedTypes;
98 ValueSet DefinedValues;
99 ForwardRefMap ForwardRefs;
104 explicit CppWriter(std::ostream &o) :
105 ModulePass((intptr_t)&ID), Out(o), uniqueNum(0), is_inline(false) {}
107 virtual const char *getPassName() const { return "C++ backend"; }
109 bool runOnModule(Module &M);
111 void printProgram(const std::string& fname, const std::string& modName );
112 void printModule(const std::string& fname, const std::string& modName );
113 void printContents(const std::string& fname, const std::string& modName );
114 void printFunction(const std::string& fname, const std::string& funcName );
115 void printFunctions();
116 void printInline(const std::string& fname, const std::string& funcName );
117 void printVariable(const std::string& fname, const std::string& varName );
118 void printType(const std::string& fname, const std::string& typeName );
120 void error(const std::string& msg);
123 void printLinkageType(GlobalValue::LinkageTypes LT);
124 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
125 void printCallingConv(unsigned cc);
126 void printEscapedString(const std::string& str);
127 void printCFP(const ConstantFP* CFP);
129 std::string getCppName(const Type* val);
130 inline void printCppName(const Type* val);
132 std::string getCppName(const Value* val);
133 inline void printCppName(const Value* val);
135 void printParamAttrs(const PAListPtr &PAL, const std::string &name);
136 bool printTypeInternal(const Type* Ty);
137 inline void printType(const Type* Ty);
138 void printTypes(const Module* M);
140 void printConstant(const Constant *CPV);
141 void printConstants(const Module* M);
143 void printVariableUses(const GlobalVariable *GV);
144 void printVariableHead(const GlobalVariable *GV);
145 void printVariableBody(const GlobalVariable *GV);
147 void printFunctionUses(const Function *F);
148 void printFunctionHead(const Function *F);
149 void printFunctionBody(const Function *F);
150 void printInstruction(const Instruction *I, const std::string& bbname);
151 std::string getOpName(Value*);
153 void printModuleBody();
156 static unsigned indent_level = 0;
157 inline std::ostream& nl(std::ostream& Out, int delta = 0) {
159 if (delta >= 0 || indent_level >= unsigned(-delta))
160 indent_level += delta;
161 for (unsigned i = 0; i < indent_level; ++i)
166 inline void in() { indent_level++; }
167 inline void out() { if (indent_level >0) indent_level--; }
170 sanitize(std::string& str) {
171 for (size_t i = 0; i < str.length(); ++i)
172 if (!isalnum(str[i]) && str[i] != '_')
177 getTypePrefix(const Type* Ty ) {
178 switch (Ty->getTypeID()) {
179 case Type::VoidTyID: return "void_";
180 case Type::IntegerTyID:
181 return std::string("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 inline 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 std::cerr << progname << ": " << msg << "\n";
216 // printCFP - Print a floating point constant .. very carefully :)
217 // This makes sure that conversion to/from floating yields the same binary
218 // result so that we don't lose precision.
219 void CppWriter::printCFP(const ConstantFP *CFP) {
220 APFloat APF = APFloat(CFP->getValueAPF()); // copy
221 if (CFP->getType() == Type::FloatTy)
222 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
223 Out << "ConstantFP::get(";
224 if (CFP->getType() == Type::DoubleTy)
225 Out << "Type::DoubleTy, ";
227 Out << "Type::FloatTy, ";
231 sprintf(Buffer, "%A", APF.convertToDouble());
232 if ((!strncmp(Buffer, "0x", 2) ||
233 !strncmp(Buffer, "-0x", 3) ||
234 !strncmp(Buffer, "+0x", 3)) &&
235 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
236 if (CFP->getType() == Type::DoubleTy)
237 Out << "BitsToDouble(" << Buffer << ")";
239 Out << "BitsToFloat((float)" << Buffer << ")";
243 std::string StrVal = ftostr(CFP->getValueAPF());
245 while (StrVal[0] == ' ')
246 StrVal.erase(StrVal.begin());
248 // Check to make sure that the stringized number is not some string like
249 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
250 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
251 ((StrVal[0] == '-' || StrVal[0] == '+') &&
252 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
253 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
254 if (CFP->getType() == Type::DoubleTy)
257 Out << StrVal << "f";
258 } else if (CFP->getType() == Type::DoubleTy)
259 Out << "BitsToDouble(0x" << std::hex
260 << CFP->getValueAPF().convertToAPInt().getZExtValue()
261 << std::dec << "ULL) /* " << StrVal << " */";
263 Out << "BitsToFloat(0x" << std::hex
264 << (uint32_t)CFP->getValueAPF().convertToAPInt().getZExtValue()
265 << std::dec << "U) /* " << StrVal << " */";
273 void CppWriter::printCallingConv(unsigned cc){
274 // Print the calling convention.
276 case CallingConv::C: Out << "CallingConv::C"; break;
277 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
278 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
279 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
280 default: Out << cc; break;
284 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
286 case GlobalValue::InternalLinkage:
287 Out << "GlobalValue::InternalLinkage"; break;
288 case GlobalValue::LinkOnceLinkage:
289 Out << "GlobalValue::LinkOnceLinkage "; break;
290 case GlobalValue::WeakLinkage:
291 Out << "GlobalValue::WeakLinkage"; break;
292 case GlobalValue::AppendingLinkage:
293 Out << "GlobalValue::AppendingLinkage"; break;
294 case GlobalValue::ExternalLinkage:
295 Out << "GlobalValue::ExternalLinkage"; break;
296 case GlobalValue::DLLImportLinkage:
297 Out << "GlobalValue::DLLImportLinkage"; break;
298 case GlobalValue::DLLExportLinkage:
299 Out << "GlobalValue::DLLExportLinkage"; break;
300 case GlobalValue::ExternalWeakLinkage:
301 Out << "GlobalValue::ExternalWeakLinkage"; break;
302 case GlobalValue::GhostLinkage:
303 Out << "GlobalValue::GhostLinkage"; break;
307 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
309 default: assert(0 && "Unknown GVar visibility");
310 case GlobalValue::DefaultVisibility:
311 Out << "GlobalValue::DefaultVisibility";
313 case GlobalValue::HiddenVisibility:
314 Out << "GlobalValue::HiddenVisibility";
316 case GlobalValue::ProtectedVisibility:
317 Out << "GlobalValue::ProtectedVisibility";
322 // printEscapedString - Print each character of the specified string, escaping
323 // it if it is not printable or if it is an escape char.
324 void CppWriter::printEscapedString(const std::string &Str) {
325 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
326 unsigned char C = Str[i];
327 if (isprint(C) && C != '"' && C != '\\') {
331 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
332 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
337 std::string CppWriter::getCppName(const Type* Ty) {
338 // First, handle the primitive types .. easy
339 if (Ty->isPrimitiveType() || Ty->isInteger()) {
340 switch (Ty->getTypeID()) {
341 case Type::VoidTyID: return "Type::VoidTy";
342 case Type::IntegerTyID: {
343 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
344 return "IntegerType::get(" + utostr(BitWidth) + ")";
346 case Type::FloatTyID: return "Type::FloatTy";
347 case Type::DoubleTyID: return "Type::DoubleTy";
348 case Type::LabelTyID: return "Type::LabelTy";
350 error("Invalid primitive type");
353 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
356 // Now, see if we've seen the type before and return that
357 TypeMap::iterator I = TypeNames.find(Ty);
358 if (I != TypeNames.end())
361 // Okay, let's build a new name for this type. Start with a prefix
362 const char* prefix = 0;
363 switch (Ty->getTypeID()) {
364 case Type::FunctionTyID: prefix = "FuncTy_"; break;
365 case Type::StructTyID: prefix = "StructTy_"; break;
366 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
367 case Type::PointerTyID: prefix = "PointerTy_"; break;
368 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
369 case Type::VectorTyID: prefix = "VectorTy_"; break;
370 default: prefix = "OtherTy_"; break; // prevent breakage
373 // See if the type has a name in the symboltable and build accordingly
374 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
377 name = std::string(prefix) + *tName;
379 name = std::string(prefix) + utostr(uniqueNum++);
383 return TypeNames[Ty] = name;
386 void CppWriter::printCppName(const Type* Ty) {
387 printEscapedString(getCppName(Ty));
390 std::string CppWriter::getCppName(const Value* val) {
392 ValueMap::iterator I = ValueNames.find(val);
393 if (I != ValueNames.end() && I->first == val)
396 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
397 name = std::string("gvar_") +
398 getTypePrefix(GV->getType()->getElementType());
399 } else if (isa<Function>(val)) {
400 name = std::string("func_");
401 } else if (const Constant* C = dyn_cast<Constant>(val)) {
402 name = std::string("const_") + getTypePrefix(C->getType());
403 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
405 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
406 Function::const_arg_iterator(Arg)) + 1;
407 name = std::string("arg_") + utostr(argNum);
408 NameSet::iterator NI = UsedNames.find(name);
409 if (NI != UsedNames.end())
410 name += std::string("_") + utostr(uniqueNum++);
411 UsedNames.insert(name);
412 return ValueNames[val] = name;
414 name = getTypePrefix(val->getType());
417 name = getTypePrefix(val->getType());
419 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
421 NameSet::iterator NI = UsedNames.find(name);
422 if (NI != UsedNames.end())
423 name += std::string("_") + utostr(uniqueNum++);
424 UsedNames.insert(name);
425 return ValueNames[val] = name;
428 void CppWriter::printCppName(const Value* val) {
429 printEscapedString(getCppName(val));
432 void CppWriter::printParamAttrs(const PAListPtr &PAL,
433 const std::string &name) {
434 Out << "PAListPtr " << name << "_PAL;";
436 if (!PAL.isEmpty()) {
437 Out << '{'; in(); nl(Out);
438 Out << "SmallVector<ParamAttrsWithIndex, 4> Attrs;"; nl(Out);
439 Out << "ParamAttrsWithIndex PAWI;"; nl(Out);
440 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
441 uint16_t index = PAL.getSlot(i).Index;
442 ParameterAttributes attrs = PAL.getSlot(i).Attrs;
443 Out << "PAWI.Index = " << index << "; PAWI.Attrs = 0 ";
444 if (attrs & ParamAttr::SExt)
445 Out << " | ParamAttr::SExt";
446 if (attrs & ParamAttr::ZExt)
447 Out << " | ParamAttr::ZExt";
448 if (attrs & ParamAttr::StructRet)
449 Out << " | ParamAttr::StructRet";
450 if (attrs & ParamAttr::InReg)
451 Out << " | ParamAttr::InReg";
452 if (attrs & ParamAttr::NoReturn)
453 Out << " | ParamAttr::NoReturn";
454 if (attrs & ParamAttr::NoUnwind)
455 Out << " | ParamAttr::NoUnwind";
456 if (attrs & ParamAttr::ByVal)
457 Out << " | ParamAttr::ByVal";
458 if (attrs & ParamAttr::NoAlias)
459 Out << " | ParamAttr::NoAlias";
460 if (attrs & ParamAttr::Nest)
461 Out << " | ParamAttr::Nest";
462 if (attrs & ParamAttr::ReadNone)
463 Out << " | ParamAttr::ReadNone";
464 if (attrs & ParamAttr::ReadOnly)
465 Out << " | ParamAttr::ReadOnly";
468 Out << "Attrs.push_back(PAWI);";
471 Out << name << "_PAL = PAListPtr::get(Attrs.begin(), Attrs.end());";
478 bool CppWriter::printTypeInternal(const Type* Ty) {
479 // We don't print definitions for primitive types
480 if (Ty->isPrimitiveType() || Ty->isInteger())
483 // If we already defined this type, we don't need to define it again.
484 if (DefinedTypes.find(Ty) != DefinedTypes.end())
487 // Everything below needs the name for the type so get it now.
488 std::string typeName(getCppName(Ty));
490 // Search the type stack for recursion. If we find it, then generate this
491 // as an OpaqueType, but make sure not to do this multiple times because
492 // the type could appear in multiple places on the stack. Once the opaque
493 // definition is issued, it must not be re-issued. Consequently we have to
494 // check the UnresolvedTypes list as well.
495 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
497 if (TI != TypeStack.end()) {
498 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
499 if (I == UnresolvedTypes.end()) {
500 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
502 UnresolvedTypes[Ty] = typeName;
507 // We're going to print a derived type which, by definition, contains other
508 // types. So, push this one we're printing onto the type stack to assist with
509 // recursive definitions.
510 TypeStack.push_back(Ty);
512 // Print the type definition
513 switch (Ty->getTypeID()) {
514 case Type::FunctionTyID: {
515 const FunctionType* FT = cast<FunctionType>(Ty);
516 Out << "std::vector<const Type*>" << typeName << "_args;";
518 FunctionType::param_iterator PI = FT->param_begin();
519 FunctionType::param_iterator PE = FT->param_end();
520 for (; PI != PE; ++PI) {
521 const Type* argTy = static_cast<const Type*>(*PI);
522 bool isForward = printTypeInternal(argTy);
523 std::string argName(getCppName(argTy));
524 Out << typeName << "_args.push_back(" << argName;
530 bool isForward = printTypeInternal(FT->getReturnType());
531 std::string retTypeName(getCppName(FT->getReturnType()));
532 Out << "FunctionType* " << typeName << " = FunctionType::get(";
533 in(); nl(Out) << "/*Result=*/" << retTypeName;
537 nl(Out) << "/*Params=*/" << typeName << "_args,";
538 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
543 case Type::StructTyID: {
544 const StructType* ST = cast<StructType>(Ty);
545 Out << "std::vector<const Type*>" << typeName << "_fields;";
547 StructType::element_iterator EI = ST->element_begin();
548 StructType::element_iterator EE = ST->element_end();
549 for (; EI != EE; ++EI) {
550 const Type* fieldTy = static_cast<const Type*>(*EI);
551 bool isForward = printTypeInternal(fieldTy);
552 std::string fieldName(getCppName(fieldTy));
553 Out << typeName << "_fields.push_back(" << fieldName;
559 Out << "StructType* " << typeName << " = StructType::get("
560 << typeName << "_fields, /*isPacked=*/"
561 << (ST->isPacked() ? "true" : "false") << ");";
565 case Type::ArrayTyID: {
566 const ArrayType* AT = cast<ArrayType>(Ty);
567 const Type* ET = AT->getElementType();
568 bool isForward = printTypeInternal(ET);
569 std::string elemName(getCppName(ET));
570 Out << "ArrayType* " << typeName << " = ArrayType::get("
571 << elemName << (isForward ? "_fwd" : "")
572 << ", " << utostr(AT->getNumElements()) << ");";
576 case Type::PointerTyID: {
577 const PointerType* PT = cast<PointerType>(Ty);
578 const Type* ET = PT->getElementType();
579 bool isForward = printTypeInternal(ET);
580 std::string elemName(getCppName(ET));
581 Out << "PointerType* " << typeName << " = PointerType::get("
582 << elemName << (isForward ? "_fwd" : "")
583 << ", " << utostr(PT->getAddressSpace()) << ");";
587 case Type::VectorTyID: {
588 const VectorType* PT = cast<VectorType>(Ty);
589 const Type* ET = PT->getElementType();
590 bool isForward = printTypeInternal(ET);
591 std::string elemName(getCppName(ET));
592 Out << "VectorType* " << typeName << " = VectorType::get("
593 << elemName << (isForward ? "_fwd" : "")
594 << ", " << utostr(PT->getNumElements()) << ");";
598 case Type::OpaqueTyID: {
599 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
604 error("Invalid TypeID");
607 // If the type had a name, make sure we recreate it.
608 const std::string* progTypeName =
609 findTypeName(TheModule->getTypeSymbolTable(),Ty);
611 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
616 // Pop us off the type stack
617 TypeStack.pop_back();
619 // Indicate that this type is now defined.
620 DefinedTypes.insert(Ty);
622 // Early resolve as many unresolved types as possible. Search the unresolved
623 // types map for the type we just printed. Now that its definition is complete
624 // we can resolve any previous references to it. This prevents a cascade of
626 TypeMap::iterator I = UnresolvedTypes.find(Ty);
627 if (I != UnresolvedTypes.end()) {
628 Out << "cast<OpaqueType>(" << I->second
629 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
631 Out << I->second << " = cast<";
632 switch (Ty->getTypeID()) {
633 case Type::FunctionTyID: Out << "FunctionType"; break;
634 case Type::ArrayTyID: Out << "ArrayType"; break;
635 case Type::StructTyID: Out << "StructType"; break;
636 case Type::VectorTyID: Out << "VectorType"; break;
637 case Type::PointerTyID: Out << "PointerType"; break;
638 case Type::OpaqueTyID: Out << "OpaqueType"; break;
639 default: Out << "NoSuchDerivedType"; break;
641 Out << ">(" << I->second << "_fwd.get());";
643 UnresolvedTypes.erase(I);
646 // Finally, separate the type definition from other with a newline.
649 // We weren't a recursive type
653 // Prints a type definition. Returns true if it could not resolve all the
654 // types in the definition but had to use a forward reference.
655 void CppWriter::printType(const Type* Ty) {
656 assert(TypeStack.empty());
658 printTypeInternal(Ty);
659 assert(TypeStack.empty());
662 void CppWriter::printTypes(const Module* M) {
663 // Walk the symbol table and print out all its types
664 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
665 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
668 // For primitive types and types already defined, just add a name
669 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
670 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
671 TNI != TypeNames.end()) {
672 Out << "mod->addTypeName(\"";
673 printEscapedString(TI->first);
674 Out << "\", " << getCppName(TI->second) << ");";
676 // For everything else, define the type
678 printType(TI->second);
682 // Add all of the global variables to the value table...
683 for (Module::const_global_iterator I = TheModule->global_begin(),
684 E = TheModule->global_end(); I != E; ++I) {
685 if (I->hasInitializer())
686 printType(I->getInitializer()->getType());
687 printType(I->getType());
690 // Add all the functions to the table
691 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
693 printType(FI->getReturnType());
694 printType(FI->getFunctionType());
695 // Add all the function arguments
696 for (Function::const_arg_iterator AI = FI->arg_begin(),
697 AE = FI->arg_end(); AI != AE; ++AI) {
698 printType(AI->getType());
701 // Add all of the basic blocks and instructions
702 for (Function::const_iterator BB = FI->begin(),
703 E = FI->end(); BB != E; ++BB) {
704 printType(BB->getType());
705 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
707 printType(I->getType());
708 for (unsigned i = 0; i < I->getNumOperands(); ++i)
709 printType(I->getOperand(i)->getType());
716 // printConstant - Print out a constant pool entry...
717 void CppWriter::printConstant(const Constant *CV) {
718 // First, if the constant is actually a GlobalValue (variable or function)
719 // or its already in the constant list then we've printed it already and we
721 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
724 std::string constName(getCppName(CV));
725 std::string typeName(getCppName(CV->getType()));
726 if (CV->isNullValue()) {
727 Out << "Constant* " << constName << " = Constant::getNullValue("
732 if (isa<GlobalValue>(CV)) {
733 // Skip variables and functions, we emit them elsewhere
736 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
737 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
738 << cast<IntegerType>(CI->getType())->getBitWidth() << ", "
739 << " \"" << CI->getValue().toStringSigned(10) << "\", 10));";
740 } else if (isa<ConstantAggregateZero>(CV)) {
741 Out << "ConstantAggregateZero* " << constName
742 << " = ConstantAggregateZero::get(" << typeName << ");";
743 } else if (isa<ConstantPointerNull>(CV)) {
744 Out << "ConstantPointerNull* " << constName
745 << " = ConstanPointerNull::get(" << typeName << ");";
746 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
747 Out << "ConstantFP* " << constName << " = ";
750 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
751 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
752 Out << "Constant* " << constName << " = ConstantArray::get(\"";
753 std::string tmp = CA->getAsString();
754 bool nullTerminate = false;
755 if (tmp[tmp.length()-1] == 0) {
756 tmp.erase(tmp.length()-1);
757 nullTerminate = true;
759 printEscapedString(tmp);
760 // Determine if we want null termination or not.
762 Out << "\", true"; // Indicate that the null terminator should be
765 Out << "\", false";// No null terminator
768 Out << "std::vector<Constant*> " << constName << "_elems;";
770 unsigned N = CA->getNumOperands();
771 for (unsigned i = 0; i < N; ++i) {
772 printConstant(CA->getOperand(i)); // recurse to print operands
773 Out << constName << "_elems.push_back("
774 << getCppName(CA->getOperand(i)) << ");";
777 Out << "Constant* " << constName << " = ConstantArray::get("
778 << typeName << ", " << constName << "_elems);";
780 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
781 Out << "std::vector<Constant*> " << constName << "_fields;";
783 unsigned N = CS->getNumOperands();
784 for (unsigned i = 0; i < N; i++) {
785 printConstant(CS->getOperand(i));
786 Out << constName << "_fields.push_back("
787 << getCppName(CS->getOperand(i)) << ");";
790 Out << "Constant* " << constName << " = ConstantStruct::get("
791 << typeName << ", " << constName << "_fields);";
792 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
793 Out << "std::vector<Constant*> " << constName << "_elems;";
795 unsigned N = CP->getNumOperands();
796 for (unsigned i = 0; i < N; ++i) {
797 printConstant(CP->getOperand(i));
798 Out << constName << "_elems.push_back("
799 << getCppName(CP->getOperand(i)) << ");";
802 Out << "Constant* " << constName << " = ConstantVector::get("
803 << typeName << ", " << constName << "_elems);";
804 } else if (isa<UndefValue>(CV)) {
805 Out << "UndefValue* " << constName << " = UndefValue::get("
807 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
808 if (CE->getOpcode() == Instruction::GetElementPtr) {
809 Out << "std::vector<Constant*> " << constName << "_indices;";
811 printConstant(CE->getOperand(0));
812 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
813 printConstant(CE->getOperand(i));
814 Out << constName << "_indices.push_back("
815 << getCppName(CE->getOperand(i)) << ");";
818 Out << "Constant* " << constName
819 << " = ConstantExpr::getGetElementPtr("
820 << getCppName(CE->getOperand(0)) << ", "
821 << "&" << constName << "_indices[0], "
822 << constName << "_indices.size()"
824 } else if (CE->isCast()) {
825 printConstant(CE->getOperand(0));
826 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
827 switch (CE->getOpcode()) {
828 default: assert(0 && "Invalid cast opcode");
829 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
830 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
831 case Instruction::SExt: Out << "Instruction::SExt"; break;
832 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
833 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
834 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
835 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
836 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
837 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
838 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
839 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
840 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
842 Out << ", " << getCppName(CE->getOperand(0)) << ", "
843 << getCppName(CE->getType()) << ");";
845 unsigned N = CE->getNumOperands();
846 for (unsigned i = 0; i < N; ++i ) {
847 printConstant(CE->getOperand(i));
849 Out << "Constant* " << constName << " = ConstantExpr::";
850 switch (CE->getOpcode()) {
851 case Instruction::Add: Out << "getAdd("; break;
852 case Instruction::Sub: Out << "getSub("; break;
853 case Instruction::Mul: Out << "getMul("; break;
854 case Instruction::UDiv: Out << "getUDiv("; break;
855 case Instruction::SDiv: Out << "getSDiv("; break;
856 case Instruction::FDiv: Out << "getFDiv("; break;
857 case Instruction::URem: Out << "getURem("; break;
858 case Instruction::SRem: Out << "getSRem("; break;
859 case Instruction::FRem: Out << "getFRem("; break;
860 case Instruction::And: Out << "getAnd("; break;
861 case Instruction::Or: Out << "getOr("; break;
862 case Instruction::Xor: Out << "getXor("; break;
863 case Instruction::ICmp:
864 Out << "getICmp(ICmpInst::ICMP_";
865 switch (CE->getPredicate()) {
866 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
867 case ICmpInst::ICMP_NE: Out << "NE"; break;
868 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
869 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
870 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
871 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
872 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
873 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
874 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
875 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
876 default: error("Invalid ICmp Predicate");
879 case Instruction::FCmp:
880 Out << "getFCmp(FCmpInst::FCMP_";
881 switch (CE->getPredicate()) {
882 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
883 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
884 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
885 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
886 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
887 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
888 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
889 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
890 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
891 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
892 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
893 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
894 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
895 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
896 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
897 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
898 default: error("Invalid FCmp Predicate");
901 case Instruction::Shl: Out << "getShl("; break;
902 case Instruction::LShr: Out << "getLShr("; break;
903 case Instruction::AShr: Out << "getAShr("; break;
904 case Instruction::Select: Out << "getSelect("; break;
905 case Instruction::ExtractElement: Out << "getExtractElement("; break;
906 case Instruction::InsertElement: Out << "getInsertElement("; break;
907 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
909 error("Invalid constant expression");
912 Out << getCppName(CE->getOperand(0));
913 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
914 Out << ", " << getCppName(CE->getOperand(i));
918 error("Bad Constant");
919 Out << "Constant* " << constName << " = 0; ";
924 void CppWriter::printConstants(const Module* M) {
925 // Traverse all the global variables looking for constant initializers
926 for (Module::const_global_iterator I = TheModule->global_begin(),
927 E = TheModule->global_end(); I != E; ++I)
928 if (I->hasInitializer())
929 printConstant(I->getInitializer());
931 // Traverse the LLVM functions looking for constants
932 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
934 // Add all of the basic blocks and instructions
935 for (Function::const_iterator BB = FI->begin(),
936 E = FI->end(); BB != E; ++BB) {
937 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
939 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
940 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
949 void CppWriter::printVariableUses(const GlobalVariable *GV) {
950 nl(Out) << "// Type Definitions";
952 printType(GV->getType());
953 if (GV->hasInitializer()) {
954 Constant* Init = GV->getInitializer();
955 printType(Init->getType());
956 if (Function* F = dyn_cast<Function>(Init)) {
957 nl(Out)<< "/ Function Declarations"; nl(Out);
958 printFunctionHead(F);
959 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
960 nl(Out) << "// Global Variable Declarations"; nl(Out);
961 printVariableHead(gv);
963 nl(Out) << "// Constant Definitions"; nl(Out);
966 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
967 nl(Out) << "// Global Variable Definitions"; nl(Out);
968 printVariableBody(gv);
973 void CppWriter::printVariableHead(const GlobalVariable *GV) {
974 nl(Out) << "GlobalVariable* " << getCppName(GV);
976 Out << " = mod->getGlobalVariable(";
977 printEscapedString(GV->getName());
978 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
979 nl(Out) << "if (!" << getCppName(GV) << ") {";
980 in(); nl(Out) << getCppName(GV);
982 Out << " = new GlobalVariable(";
983 nl(Out) << "/*Type=*/";
984 printCppName(GV->getType()->getElementType());
986 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
988 nl(Out) << "/*Linkage=*/";
989 printLinkageType(GV->getLinkage());
991 nl(Out) << "/*Initializer=*/0, ";
992 if (GV->hasInitializer()) {
993 Out << "// has initializer, specified below";
995 nl(Out) << "/*Name=*/\"";
996 printEscapedString(GV->getName());
1001 if (GV->hasSection()) {
1003 Out << "->setSection(\"";
1004 printEscapedString(GV->getSection());
1008 if (GV->getAlignment()) {
1010 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1013 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1015 Out << "->setVisibility(";
1016 printVisibilityType(GV->getVisibility());
1021 out(); Out << "}"; nl(Out);
1025 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1026 if (GV->hasInitializer()) {
1028 Out << "->setInitializer(";
1029 Out << getCppName(GV->getInitializer()) << ");";
1034 std::string CppWriter::getOpName(Value* V) {
1035 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1036 return getCppName(V);
1038 // See if its alread in the map of forward references, if so just return the
1039 // name we already set up for it
1040 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1041 if (I != ForwardRefs.end())
1044 // This is a new forward reference. Generate a unique name for it
1045 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1047 // Yes, this is a hack. An Argument is the smallest instantiable value that
1048 // we can make as a placeholder for the real value. We'll replace these
1049 // Argument instances later.
1050 Out << "Argument* " << result << " = new Argument("
1051 << getCppName(V->getType()) << ");";
1053 ForwardRefs[V] = result;
1057 // printInstruction - This member is called for each Instruction in a function.
1058 void CppWriter::printInstruction(const Instruction *I,
1059 const std::string& bbname) {
1060 std::string iName(getCppName(I));
1062 // Before we emit this instruction, we need to take care of generating any
1063 // forward references. So, we get the names of all the operands in advance
1064 std::string* opNames = new std::string[I->getNumOperands()];
1065 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1066 opNames[i] = getOpName(I->getOperand(i));
1069 switch (I->getOpcode()) {
1070 case Instruction::Ret: {
1071 const ReturnInst* ret = cast<ReturnInst>(I);
1072 Out << "ReturnInst::Create("
1073 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1076 case Instruction::Br: {
1077 const BranchInst* br = cast<BranchInst>(I);
1078 Out << "BranchInst::Create(" ;
1079 if (br->getNumOperands() == 3 ) {
1080 Out << opNames[0] << ", "
1081 << opNames[1] << ", "
1082 << opNames[2] << ", ";
1084 } else if (br->getNumOperands() == 1) {
1085 Out << opNames[0] << ", ";
1087 error("Branch with 2 operands?");
1089 Out << bbname << ");";
1092 case Instruction::Switch: {
1093 const SwitchInst* sw = cast<SwitchInst>(I);
1094 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1095 << opNames[0] << ", "
1096 << opNames[1] << ", "
1097 << sw->getNumCases() << ", " << bbname << ");";
1099 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1100 Out << iName << "->addCase("
1101 << opNames[i] << ", "
1102 << opNames[i+1] << ");";
1107 case Instruction::Invoke: {
1108 const InvokeInst* inv = cast<InvokeInst>(I);
1109 Out << "std::vector<Value*> " << iName << "_params;";
1111 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1112 Out << iName << "_params.push_back("
1113 << opNames[i] << ");";
1116 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1117 << opNames[0] << ", "
1118 << opNames[1] << ", "
1119 << opNames[2] << ", "
1120 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1121 printEscapedString(inv->getName());
1122 Out << "\", " << bbname << ");";
1123 nl(Out) << iName << "->setCallingConv(";
1124 printCallingConv(inv->getCallingConv());
1126 printParamAttrs(inv->getParamAttrs(), iName);
1127 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1131 case Instruction::Unwind: {
1132 Out << "new UnwindInst("
1136 case Instruction::Unreachable:{
1137 Out << "new UnreachableInst("
1141 case Instruction::Add:
1142 case Instruction::Sub:
1143 case Instruction::Mul:
1144 case Instruction::UDiv:
1145 case Instruction::SDiv:
1146 case Instruction::FDiv:
1147 case Instruction::URem:
1148 case Instruction::SRem:
1149 case Instruction::FRem:
1150 case Instruction::And:
1151 case Instruction::Or:
1152 case Instruction::Xor:
1153 case Instruction::Shl:
1154 case Instruction::LShr:
1155 case Instruction::AShr:{
1156 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1157 switch (I->getOpcode()) {
1158 case Instruction::Add: Out << "Instruction::Add"; break;
1159 case Instruction::Sub: Out << "Instruction::Sub"; break;
1160 case Instruction::Mul: Out << "Instruction::Mul"; break;
1161 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1162 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1163 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1164 case Instruction::URem:Out << "Instruction::URem"; break;
1165 case Instruction::SRem:Out << "Instruction::SRem"; break;
1166 case Instruction::FRem:Out << "Instruction::FRem"; break;
1167 case Instruction::And: Out << "Instruction::And"; break;
1168 case Instruction::Or: Out << "Instruction::Or"; break;
1169 case Instruction::Xor: Out << "Instruction::Xor"; break;
1170 case Instruction::Shl: Out << "Instruction::Shl"; break;
1171 case Instruction::LShr:Out << "Instruction::LShr"; break;
1172 case Instruction::AShr:Out << "Instruction::AShr"; break;
1173 default: Out << "Instruction::BadOpCode"; break;
1175 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1176 printEscapedString(I->getName());
1177 Out << "\", " << bbname << ");";
1180 case Instruction::FCmp: {
1181 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1182 switch (cast<FCmpInst>(I)->getPredicate()) {
1183 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1184 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1185 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1186 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1187 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1188 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1189 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1190 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1191 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1192 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1193 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1194 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1195 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1196 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1197 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1198 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1199 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1201 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1202 printEscapedString(I->getName());
1203 Out << "\", " << bbname << ");";
1206 case Instruction::ICmp: {
1207 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1208 switch (cast<ICmpInst>(I)->getPredicate()) {
1209 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1210 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1211 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1212 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1213 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1214 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1215 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1216 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1217 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1218 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1219 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1221 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1222 printEscapedString(I->getName());
1223 Out << "\", " << bbname << ");";
1226 case Instruction::Malloc: {
1227 const MallocInst* mallocI = cast<MallocInst>(I);
1228 Out << "MallocInst* " << iName << " = new MallocInst("
1229 << getCppName(mallocI->getAllocatedType()) << ", ";
1230 if (mallocI->isArrayAllocation())
1231 Out << opNames[0] << ", " ;
1233 printEscapedString(mallocI->getName());
1234 Out << "\", " << bbname << ");";
1235 if (mallocI->getAlignment())
1236 nl(Out) << iName << "->setAlignment("
1237 << mallocI->getAlignment() << ");";
1240 case Instruction::Free: {
1241 Out << "FreeInst* " << iName << " = new FreeInst("
1242 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1245 case Instruction::Alloca: {
1246 const AllocaInst* allocaI = cast<AllocaInst>(I);
1247 Out << "AllocaInst* " << iName << " = new AllocaInst("
1248 << getCppName(allocaI->getAllocatedType()) << ", ";
1249 if (allocaI->isArrayAllocation())
1250 Out << opNames[0] << ", ";
1252 printEscapedString(allocaI->getName());
1253 Out << "\", " << bbname << ");";
1254 if (allocaI->getAlignment())
1255 nl(Out) << iName << "->setAlignment("
1256 << allocaI->getAlignment() << ");";
1259 case Instruction::Load:{
1260 const LoadInst* load = cast<LoadInst>(I);
1261 Out << "LoadInst* " << iName << " = new LoadInst("
1262 << opNames[0] << ", \"";
1263 printEscapedString(load->getName());
1264 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1265 << ", " << bbname << ");";
1268 case Instruction::Store: {
1269 const StoreInst* store = cast<StoreInst>(I);
1270 Out << "StoreInst* " << iName << " = new StoreInst("
1271 << opNames[0] << ", "
1272 << opNames[1] << ", "
1273 << (store->isVolatile() ? "true" : "false")
1274 << ", " << bbname << ");";
1277 case Instruction::GetElementPtr: {
1278 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1279 if (gep->getNumOperands() <= 2) {
1280 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1282 if (gep->getNumOperands() == 2)
1283 Out << ", " << opNames[1];
1285 Out << "std::vector<Value*> " << iName << "_indices;";
1287 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1288 Out << iName << "_indices.push_back("
1289 << opNames[i] << ");";
1292 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1293 << opNames[0] << ", " << iName << "_indices.begin(), "
1294 << iName << "_indices.end()";
1297 printEscapedString(gep->getName());
1298 Out << "\", " << bbname << ");";
1301 case Instruction::PHI: {
1302 const PHINode* phi = cast<PHINode>(I);
1304 Out << "PHINode* " << iName << " = PHINode::Create("
1305 << getCppName(phi->getType()) << ", \"";
1306 printEscapedString(phi->getName());
1307 Out << "\", " << bbname << ");";
1308 nl(Out) << iName << "->reserveOperandSpace("
1309 << phi->getNumIncomingValues()
1312 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1313 Out << iName << "->addIncoming("
1314 << opNames[i] << ", " << opNames[i+1] << ");";
1319 case Instruction::Trunc:
1320 case Instruction::ZExt:
1321 case Instruction::SExt:
1322 case Instruction::FPTrunc:
1323 case Instruction::FPExt:
1324 case Instruction::FPToUI:
1325 case Instruction::FPToSI:
1326 case Instruction::UIToFP:
1327 case Instruction::SIToFP:
1328 case Instruction::PtrToInt:
1329 case Instruction::IntToPtr:
1330 case Instruction::BitCast: {
1331 const CastInst* cst = cast<CastInst>(I);
1332 Out << "CastInst* " << iName << " = new ";
1333 switch (I->getOpcode()) {
1334 case Instruction::Trunc: Out << "TruncInst"; break;
1335 case Instruction::ZExt: Out << "ZExtInst"; break;
1336 case Instruction::SExt: Out << "SExtInst"; break;
1337 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1338 case Instruction::FPExt: Out << "FPExtInst"; break;
1339 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1340 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1341 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1342 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1343 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1344 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1345 case Instruction::BitCast: Out << "BitCastInst"; break;
1346 default: assert(!"Unreachable"); break;
1348 Out << "(" << opNames[0] << ", "
1349 << getCppName(cst->getType()) << ", \"";
1350 printEscapedString(cst->getName());
1351 Out << "\", " << bbname << ");";
1354 case Instruction::Call:{
1355 const CallInst* call = cast<CallInst>(I);
1356 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1357 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1358 << getCppName(ila->getFunctionType()) << ", \""
1359 << ila->getAsmString() << "\", \""
1360 << ila->getConstraintString() << "\","
1361 << (ila->hasSideEffects() ? "true" : "false") << ");";
1364 if (call->getNumOperands() > 2) {
1365 Out << "std::vector<Value*> " << iName << "_params;";
1367 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1368 Out << iName << "_params.push_back(" << opNames[i] << ");";
1371 Out << "CallInst* " << iName << " = CallInst::Create("
1372 << opNames[0] << ", " << iName << "_params.begin(), "
1373 << iName << "_params.end(), \"";
1374 } else if (call->getNumOperands() == 2) {
1375 Out << "CallInst* " << iName << " = CallInst::Create("
1376 << opNames[0] << ", " << opNames[1] << ", \"";
1378 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1381 printEscapedString(call->getName());
1382 Out << "\", " << bbname << ");";
1383 nl(Out) << iName << "->setCallingConv(";
1384 printCallingConv(call->getCallingConv());
1386 nl(Out) << iName << "->setTailCall("
1387 << (call->isTailCall() ? "true":"false");
1389 printParamAttrs(call->getParamAttrs(), iName);
1390 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1394 case Instruction::Select: {
1395 const SelectInst* sel = cast<SelectInst>(I);
1396 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1397 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1398 printEscapedString(sel->getName());
1399 Out << "\", " << bbname << ");";
1402 case Instruction::UserOp1:
1404 case Instruction::UserOp2: {
1405 /// FIXME: What should be done here?
1408 case Instruction::VAArg: {
1409 const VAArgInst* va = cast<VAArgInst>(I);
1410 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1411 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1412 printEscapedString(va->getName());
1413 Out << "\", " << bbname << ");";
1416 case Instruction::ExtractElement: {
1417 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1418 Out << "ExtractElementInst* " << getCppName(eei)
1419 << " = new ExtractElementInst(" << opNames[0]
1420 << ", " << opNames[1] << ", \"";
1421 printEscapedString(eei->getName());
1422 Out << "\", " << bbname << ");";
1425 case Instruction::InsertElement: {
1426 const InsertElementInst* iei = cast<InsertElementInst>(I);
1427 Out << "InsertElementInst* " << getCppName(iei)
1428 << " = InsertElementInst::Create(" << opNames[0]
1429 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1430 printEscapedString(iei->getName());
1431 Out << "\", " << bbname << ");";
1434 case Instruction::ShuffleVector: {
1435 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1436 Out << "ShuffleVectorInst* " << getCppName(svi)
1437 << " = new ShuffleVectorInst(" << opNames[0]
1438 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1439 printEscapedString(svi->getName());
1440 Out << "\", " << bbname << ");";
1444 DefinedValues.insert(I);
1449 // Print out the types, constants and declarations needed by one function
1450 void CppWriter::printFunctionUses(const Function* F) {
1451 nl(Out) << "// Type Definitions"; nl(Out);
1453 // Print the function's return type
1454 printType(F->getReturnType());
1456 // Print the function's function type
1457 printType(F->getFunctionType());
1459 // Print the types of each of the function's arguments
1460 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1462 printType(AI->getType());
1466 // Print type definitions for every type referenced by an instruction and
1467 // make a note of any global values or constants that are referenced
1468 SmallPtrSet<GlobalValue*,64> gvs;
1469 SmallPtrSet<Constant*,64> consts;
1470 for (Function::const_iterator BB = F->begin(), BE = F->end();
1472 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1474 // Print the type of the instruction itself
1475 printType(I->getType());
1477 // Print the type of each of the instruction's operands
1478 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1479 Value* operand = I->getOperand(i);
1480 printType(operand->getType());
1482 // If the operand references a GVal or Constant, make a note of it
1483 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1485 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1486 if (GVar->hasInitializer())
1487 consts.insert(GVar->getInitializer());
1488 } else if (Constant* C = dyn_cast<Constant>(operand))
1494 // Print the function declarations for any functions encountered
1495 nl(Out) << "// Function Declarations"; nl(Out);
1496 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1498 if (Function* Fun = dyn_cast<Function>(*I)) {
1499 if (!is_inline || Fun != F)
1500 printFunctionHead(Fun);
1504 // Print the global variable declarations for any variables encountered
1505 nl(Out) << "// Global Variable Declarations"; nl(Out);
1506 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1508 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1509 printVariableHead(F);
1512 // Print the constants found
1513 nl(Out) << "// Constant Definitions"; nl(Out);
1514 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1515 E = consts.end(); I != E; ++I) {
1519 // Process the global variables definitions now that all the constants have
1520 // been emitted. These definitions just couple the gvars with their constant
1522 nl(Out) << "// Global Variable Definitions"; nl(Out);
1523 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1525 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1526 printVariableBody(GV);
1530 void CppWriter::printFunctionHead(const Function* F) {
1531 nl(Out) << "Function* " << getCppName(F);
1533 Out << " = mod->getFunction(\"";
1534 printEscapedString(F->getName());
1535 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1536 nl(Out) << "if (!" << getCppName(F) << ") {";
1537 nl(Out) << getCppName(F);
1539 Out<< " = Function::Create(";
1540 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1541 nl(Out) << "/*Linkage=*/";
1542 printLinkageType(F->getLinkage());
1544 nl(Out) << "/*Name=*/\"";
1545 printEscapedString(F->getName());
1546 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1549 Out << "->setCallingConv(";
1550 printCallingConv(F->getCallingConv());
1553 if (F->hasSection()) {
1555 Out << "->setSection(\"" << F->getSection() << "\");";
1558 if (F->getAlignment()) {
1560 Out << "->setAlignment(" << F->getAlignment() << ");";
1563 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1565 Out << "->setVisibility(";
1566 printVisibilityType(F->getVisibility());
1570 if (F->hasCollector()) {
1572 Out << "->setCollector(\"" << F->getCollector() << "\");";
1579 printParamAttrs(F->getParamAttrs(), getCppName(F));
1581 Out << "->setParamAttrs(" << getCppName(F) << "_PAL);";
1585 void CppWriter::printFunctionBody(const Function *F) {
1586 if (F->isDeclaration())
1587 return; // external functions have no bodies.
1589 // Clear the DefinedValues and ForwardRefs maps because we can't have
1590 // cross-function forward refs
1591 ForwardRefs.clear();
1592 DefinedValues.clear();
1594 // Create all the argument values
1596 if (!F->arg_empty()) {
1597 Out << "Function::arg_iterator args = " << getCppName(F)
1598 << "->arg_begin();";
1601 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1603 Out << "Value* " << getCppName(AI) << " = args++;";
1605 if (AI->hasName()) {
1606 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1612 // Create all the basic blocks
1614 for (Function::const_iterator BI = F->begin(), BE = F->end();
1616 std::string bbname(getCppName(BI));
1617 Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1619 printEscapedString(BI->getName());
1620 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1624 // Output all of its basic blocks... for the function
1625 for (Function::const_iterator BI = F->begin(), BE = F->end();
1627 std::string bbname(getCppName(BI));
1628 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1631 // Output all of the instructions in the basic block...
1632 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1634 printInstruction(I,bbname);
1638 // Loop over the ForwardRefs and resolve them now that all instructions
1640 if (!ForwardRefs.empty()) {
1641 nl(Out) << "// Resolve Forward References";
1645 while (!ForwardRefs.empty()) {
1646 ForwardRefMap::iterator I = ForwardRefs.begin();
1647 Out << I->second << "->replaceAllUsesWith("
1648 << getCppName(I->first) << "); delete " << I->second << ";";
1650 ForwardRefs.erase(I);
1654 void CppWriter::printInline(const std::string& fname,
1655 const std::string& func) {
1656 const Function* F = TheModule->getFunction(func);
1658 error(std::string("Function '") + func + "' not found in input module");
1661 if (F->isDeclaration()) {
1662 error(std::string("Function '") + func + "' is external!");
1665 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1667 unsigned arg_count = 1;
1668 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1670 Out << ", Value* arg_" << arg_count;
1675 printFunctionUses(F);
1676 printFunctionBody(F);
1678 Out << "return " << getCppName(F->begin()) << ";";
1683 void CppWriter::printModuleBody() {
1684 // Print out all the type definitions
1685 nl(Out) << "// Type Definitions"; nl(Out);
1686 printTypes(TheModule);
1688 // Functions can call each other and global variables can reference them so
1689 // define all the functions first before emitting their function bodies.
1690 nl(Out) << "// Function Declarations"; nl(Out);
1691 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1693 printFunctionHead(I);
1695 // Process the global variables declarations. We can't initialze them until
1696 // after the constants are printed so just print a header for each global
1697 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1698 for (Module::const_global_iterator I = TheModule->global_begin(),
1699 E = TheModule->global_end(); I != E; ++I) {
1700 printVariableHead(I);
1703 // Print out all the constants definitions. Constants don't recurse except
1704 // through GlobalValues. All GlobalValues have been declared at this point
1705 // so we can proceed to generate the constants.
1706 nl(Out) << "// Constant Definitions"; nl(Out);
1707 printConstants(TheModule);
1709 // Process the global variables definitions now that all the constants have
1710 // been emitted. These definitions just couple the gvars with their constant
1712 nl(Out) << "// Global Variable Definitions"; nl(Out);
1713 for (Module::const_global_iterator I = TheModule->global_begin(),
1714 E = TheModule->global_end(); I != E; ++I) {
1715 printVariableBody(I);
1718 // Finally, we can safely put out all of the function bodies.
1719 nl(Out) << "// Function Definitions"; nl(Out);
1720 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1722 if (!I->isDeclaration()) {
1723 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1727 printFunctionBody(I);
1734 void CppWriter::printProgram(const std::string& fname,
1735 const std::string& mName) {
1736 Out << "#include <llvm/Module.h>\n";
1737 Out << "#include <llvm/DerivedTypes.h>\n";
1738 Out << "#include <llvm/Constants.h>\n";
1739 Out << "#include <llvm/GlobalVariable.h>\n";
1740 Out << "#include <llvm/Function.h>\n";
1741 Out << "#include <llvm/CallingConv.h>\n";
1742 Out << "#include <llvm/BasicBlock.h>\n";
1743 Out << "#include <llvm/Instructions.h>\n";
1744 Out << "#include <llvm/InlineAsm.h>\n";
1745 Out << "#include <llvm/Support/MathExtras.h>\n";
1746 Out << "#include <llvm/Pass.h>\n";
1747 Out << "#include <llvm/PassManager.h>\n";
1748 Out << "#include <llvm/ADT/SmallVector.h>\n";
1749 Out << "#include <llvm/Analysis/Verifier.h>\n";
1750 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1751 Out << "#include <algorithm>\n";
1752 Out << "#include <iostream>\n\n";
1753 Out << "using namespace llvm;\n\n";
1754 Out << "Module* " << fname << "();\n\n";
1755 Out << "int main(int argc, char**argv) {\n";
1756 Out << " Module* Mod = " << fname << "();\n";
1757 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1758 Out << " std::cerr.flush();\n";
1759 Out << " std::cout.flush();\n";
1760 Out << " PassManager PM;\n";
1761 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1762 Out << " PM.run(*Mod);\n";
1763 Out << " return 0;\n";
1765 printModule(fname,mName);
1768 void CppWriter::printModule(const std::string& fname,
1769 const std::string& mName) {
1770 nl(Out) << "Module* " << fname << "() {";
1771 nl(Out,1) << "// Module Construction";
1772 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1773 if (!TheModule->getTargetTriple().empty()) {
1774 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1776 if (!TheModule->getTargetTriple().empty()) {
1777 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1781 if (!TheModule->getModuleInlineAsm().empty()) {
1782 nl(Out) << "mod->setModuleInlineAsm(\"";
1783 printEscapedString(TheModule->getModuleInlineAsm());
1788 // Loop over the dependent libraries and emit them.
1789 Module::lib_iterator LI = TheModule->lib_begin();
1790 Module::lib_iterator LE = TheModule->lib_end();
1792 Out << "mod->addLibrary(\"" << *LI << "\");";
1797 nl(Out) << "return mod;";
1802 void CppWriter::printContents(const std::string& fname,
1803 const std::string& mName) {
1804 Out << "\nModule* " << fname << "(Module *mod) {\n";
1805 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1807 Out << "\nreturn mod;\n";
1811 void CppWriter::printFunction(const std::string& fname,
1812 const std::string& funcName) {
1813 const Function* F = TheModule->getFunction(funcName);
1815 error(std::string("Function '") + funcName + "' not found in input module");
1818 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1819 printFunctionUses(F);
1820 printFunctionHead(F);
1821 printFunctionBody(F);
1822 Out << "return " << getCppName(F) << ";\n";
1826 void CppWriter::printFunctions() {
1827 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1828 Module::const_iterator I = funcs.begin();
1829 Module::const_iterator IE = funcs.end();
1831 for (; I != IE; ++I) {
1832 const Function &func = *I;
1833 if (!func.isDeclaration()) {
1834 std::string name("define_");
1835 name += func.getName();
1836 printFunction(name, func.getName());
1841 void CppWriter::printVariable(const std::string& fname,
1842 const std::string& varName) {
1843 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1846 error(std::string("Variable '") + varName + "' not found in input module");
1849 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1850 printVariableUses(GV);
1851 printVariableHead(GV);
1852 printVariableBody(GV);
1853 Out << "return " << getCppName(GV) << ";\n";
1857 void CppWriter::printType(const std::string& fname,
1858 const std::string& typeName) {
1859 const Type* Ty = TheModule->getTypeByName(typeName);
1861 error(std::string("Type '") + typeName + "' not found in input module");
1864 Out << "\nType* " << fname << "(Module *mod) {\n";
1866 Out << "return " << getCppName(Ty) << ";\n";
1870 bool CppWriter::runOnModule(Module &M) {
1874 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1876 // Get the name of the function we're supposed to generate
1877 std::string fname = FuncName.getValue();
1879 // Get the name of the thing we are to generate
1880 std::string tgtname = NameToGenerate.getValue();
1881 if (GenerationType == GenModule ||
1882 GenerationType == GenContents ||
1883 GenerationType == GenProgram ||
1884 GenerationType == GenFunctions) {
1885 if (tgtname == "!bad!") {
1886 if (M.getModuleIdentifier() == "-")
1887 tgtname = "<stdin>";
1889 tgtname = M.getModuleIdentifier();
1891 } else if (tgtname == "!bad!")
1892 error("You must use the -for option with -gen-{function,variable,type}");
1894 switch (WhatToGenerate(GenerationType)) {
1897 fname = "makeLLVMModule";
1898 printProgram(fname,tgtname);
1902 fname = "makeLLVMModule";
1903 printModule(fname,tgtname);
1907 fname = "makeLLVMModuleContents";
1908 printContents(fname,tgtname);
1912 fname = "makeLLVMFunction";
1913 printFunction(fname,tgtname);
1920 fname = "makeLLVMInline";
1921 printInline(fname,tgtname);
1925 fname = "makeLLVMVariable";
1926 printVariable(fname,tgtname);
1930 fname = "makeLLVMType";
1931 printType(fname,tgtname);
1934 error("Invalid generation option");
1941 char CppWriter::ID = 0;
1943 //===----------------------------------------------------------------------===//
1944 // External Interface declaration
1945 //===----------------------------------------------------------------------===//
1947 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
1949 CodeGenFileType FileType,
1951 if (FileType != TargetMachine::AssemblyFile) return true;
1952 PM.add(new CppWriter(o));