1 //===-- CppWriter.cpp - Printing LLVM IR as a C++ Source File -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the writing of the LLVM IR as a set of C++ calls to the
11 // LLVM IR interface. The input module is assumed to be verified.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CallingConv.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/Instruction.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/ParameterAttributes.h"
22 #include "llvm/Module.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Config/config.h"
37 static cl::opt<std::string>
38 FuncName("funcname", cl::desc("Specify the name of the generated function"),
39 cl::value_desc("function name"));
51 static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
52 cl::desc("Choose what kind of output to generate"),
55 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
56 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
57 clEnumValN(GenContents,"gen-contents", "Generate contents of a module"),
58 clEnumValN(GenFunction,"gen-function", "Generate a function definition"),
59 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
60 clEnumValN(GenVariable,"gen-variable", "Generate a variable definition"),
61 clEnumValN(GenType, "gen-type", "Generate a type definition"),
66 static cl::opt<std::string> NameToGenerate("for", cl::Optional,
67 cl::desc("Specify the name of the thing to generate"),
71 typedef std::vector<const Type*> TypeList;
72 typedef std::map<const Type*,std::string> TypeMap;
73 typedef std::map<const Value*,std::string> ValueMap;
74 typedef std::set<std::string> NameSet;
75 typedef std::set<const Type*> TypeSet;
76 typedef std::set<const Value*> ValueSet;
77 typedef std::map<const Value*,std::string> ForwardRefMap;
82 const Module *TheModule;
86 TypeMap UnresolvedTypes;
90 ValueSet DefinedValues;
91 ForwardRefMap ForwardRefs;
95 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
96 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
97 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
99 const Module* getModule() { return TheModule; }
101 void printProgram(const std::string& fname, const std::string& modName );
102 void printModule(const std::string& fname, const std::string& modName );
103 void printContents(const std::string& fname, const std::string& modName );
104 void printFunction(const std::string& fname, const std::string& funcName );
105 void printInline(const std::string& fname, const std::string& funcName );
106 void printVariable(const std::string& fname, const std::string& varName );
107 void printType(const std::string& fname, const std::string& typeName );
109 void error(const std::string& msg);
112 void printLinkageType(GlobalValue::LinkageTypes LT);
113 void printCallingConv(unsigned cc);
114 void printEscapedString(const std::string& str);
115 void printCFP(const ConstantFP* CFP);
117 std::string getCppName(const Type* val);
118 inline void printCppName(const Type* val);
120 std::string getCppName(const Value* val);
121 inline void printCppName(const Value* val);
123 bool printTypeInternal(const Type* Ty);
124 inline void printType(const Type* Ty);
125 void printTypes(const Module* M);
127 void printConstant(const Constant *CPV);
128 void printConstants(const Module* M);
130 void printVariableUses(const GlobalVariable *GV);
131 void printVariableHead(const GlobalVariable *GV);
132 void printVariableBody(const GlobalVariable *GV);
134 void printFunctionUses(const Function *F);
135 void printFunctionHead(const Function *F);
136 void printFunctionBody(const Function *F);
137 void printInstruction(const Instruction *I, const std::string& bbname);
138 std::string getOpName(Value*);
140 void printModuleBody();
144 static unsigned indent_level = 0;
145 inline std::ostream& nl(std::ostream& Out, int delta = 0) {
147 if (delta >= 0 || indent_level >= unsigned(-delta))
148 indent_level += delta;
149 for (unsigned i = 0; i < indent_level; ++i)
154 inline void in() { indent_level++; }
155 inline void out() { if (indent_level >0) indent_level--; }
158 sanitize(std::string& str) {
159 for (size_t i = 0; i < str.length(); ++i)
160 if (!isalnum(str[i]) && str[i] != '_')
165 getTypePrefix(const Type* Ty ) {
166 switch (Ty->getTypeID()) {
167 case Type::VoidTyID: return "void_";
168 case Type::IntegerTyID:
169 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
171 case Type::FloatTyID: return "float_";
172 case Type::DoubleTyID: return "double_";
173 case Type::LabelTyID: return "label_";
174 case Type::FunctionTyID: return "func_";
175 case Type::StructTyID: return "struct_";
176 case Type::ArrayTyID: return "array_";
177 case Type::PointerTyID: return "ptr_";
178 case Type::VectorTyID: return "packed_";
179 case Type::OpaqueTyID: return "opaque_";
180 default: return "other_";
185 // Looks up the type in the symbol table and returns a pointer to its name or
186 // a null pointer if it wasn't found. Note that this isn't the same as the
187 // Mode::getTypeName function which will return an empty string, not a null
188 // pointer if the name is not found.
189 inline const std::string*
190 findTypeName(const TypeSymbolTable& ST, const Type* Ty)
192 TypeSymbolTable::const_iterator TI = ST.begin();
193 TypeSymbolTable::const_iterator TE = ST.end();
194 for (;TI != TE; ++TI)
195 if (TI->second == Ty)
201 CppWriter::error(const std::string& msg) {
202 std::cerr << progname << ": " << msg << "\n";
206 // printCFP - Print a floating point constant .. very carefully :)
207 // This makes sure that conversion to/from floating yields the same binary
208 // result so that we don't lose precision.
210 CppWriter::printCFP(const ConstantFP *CFP) {
211 Out << "ConstantFP::get(";
212 if (CFP->getType() == Type::DoubleTy)
213 Out << "Type::DoubleTy, ";
215 Out << "Type::FloatTy, ";
218 sprintf(Buffer, "%A", CFP->getValue());
219 if ((!strncmp(Buffer, "0x", 2) ||
220 !strncmp(Buffer, "-0x", 3) ||
221 !strncmp(Buffer, "+0x", 3)) &&
222 (atof(Buffer) == CFP->getValue()))
223 if (CFP->getType() == Type::DoubleTy)
224 Out << "BitsToDouble(" << Buffer << ")";
226 Out << "BitsToFloat(" << Buffer << ")";
229 std::string StrVal = ftostr(CFP->getValue());
231 while (StrVal[0] == ' ')
232 StrVal.erase(StrVal.begin());
234 // Check to make sure that the stringized number is not some string like
235 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
236 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
237 ((StrVal[0] == '-' || StrVal[0] == '+') &&
238 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
239 (atof(StrVal.c_str()) == CFP->getValue()))
240 if (CFP->getType() == Type::DoubleTy)
244 else if (CFP->getType() == Type::DoubleTy)
245 Out << "BitsToDouble(0x" << std::hex << DoubleToBits(CFP->getValue())
246 << std::dec << "ULL) /* " << StrVal << " */";
248 Out << "BitsToFloat(0x" << std::hex << FloatToBits(CFP->getValue())
249 << std::dec << "U) /* " << StrVal << " */";
257 CppWriter::printCallingConv(unsigned cc){
258 // Print the calling convention.
260 case CallingConv::C: Out << "CallingConv::C"; break;
261 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
262 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
263 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
264 default: Out << cc; break;
269 CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
271 case GlobalValue::InternalLinkage:
272 Out << "GlobalValue::InternalLinkage"; break;
273 case GlobalValue::LinkOnceLinkage:
274 Out << "GlobalValue::LinkOnceLinkage "; break;
275 case GlobalValue::WeakLinkage:
276 Out << "GlobalValue::WeakLinkage"; break;
277 case GlobalValue::AppendingLinkage:
278 Out << "GlobalValue::AppendingLinkage"; break;
279 case GlobalValue::ExternalLinkage:
280 Out << "GlobalValue::ExternalLinkage"; break;
281 case GlobalValue::DLLImportLinkage:
282 Out << "GlobalValue::DllImportLinkage"; break;
283 case GlobalValue::DLLExportLinkage:
284 Out << "GlobalValue::DllExportLinkage"; break;
285 case GlobalValue::ExternalWeakLinkage:
286 Out << "GlobalValue::ExternalWeakLinkage"; break;
287 case GlobalValue::GhostLinkage:
288 Out << "GlobalValue::GhostLinkage"; break;
292 // printEscapedString - Print each character of the specified string, escaping
293 // it if it is not printable or if it is an escape char.
295 CppWriter::printEscapedString(const std::string &Str) {
296 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
297 unsigned char C = Str[i];
298 if (isprint(C) && C != '"' && C != '\\') {
302 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
303 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
309 CppWriter::getCppName(const Type* Ty)
311 // First, handle the primitive types .. easy
312 if (Ty->isPrimitiveType() || Ty->isInteger()) {
313 switch (Ty->getTypeID()) {
314 case Type::VoidTyID: return "Type::VoidTy";
315 case Type::IntegerTyID: {
316 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
317 return "IntegerType::get(" + utostr(BitWidth) + ")";
319 case Type::FloatTyID: return "Type::FloatTy";
320 case Type::DoubleTyID: return "Type::DoubleTy";
321 case Type::LabelTyID: return "Type::LabelTy";
323 error("Invalid primitive type");
326 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
329 // Now, see if we've seen the type before and return that
330 TypeMap::iterator I = TypeNames.find(Ty);
331 if (I != TypeNames.end())
334 // Okay, let's build a new name for this type. Start with a prefix
335 const char* prefix = 0;
336 switch (Ty->getTypeID()) {
337 case Type::FunctionTyID: prefix = "FuncTy_"; break;
338 case Type::StructTyID: prefix = "StructTy_"; break;
339 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
340 case Type::PointerTyID: prefix = "PointerTy_"; break;
341 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
342 case Type::VectorTyID: prefix = "VectorTy_"; break;
343 default: prefix = "OtherTy_"; break; // prevent breakage
346 // See if the type has a name in the symboltable and build accordingly
347 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
350 name = std::string(prefix) + *tName;
352 name = std::string(prefix) + utostr(uniqueNum++);
356 return TypeNames[Ty] = name;
360 CppWriter::printCppName(const Type* Ty)
362 printEscapedString(getCppName(Ty));
366 CppWriter::getCppName(const Value* val) {
368 ValueMap::iterator I = ValueNames.find(val);
369 if (I != ValueNames.end() && I->first == val)
372 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
373 name = std::string("gvar_") +
374 getTypePrefix(GV->getType()->getElementType());
375 } else if (isa<Function>(val)) {
376 name = std::string("func_");
377 } else if (const Constant* C = dyn_cast<Constant>(val)) {
378 name = std::string("const_") + getTypePrefix(C->getType());
379 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
381 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
382 Function::const_arg_iterator(Arg)) + 1;
383 name = std::string("arg_") + utostr(argNum);
384 NameSet::iterator NI = UsedNames.find(name);
385 if (NI != UsedNames.end())
386 name += std::string("_") + utostr(uniqueNum++);
387 UsedNames.insert(name);
388 return ValueNames[val] = name;
390 name = getTypePrefix(val->getType());
393 name = getTypePrefix(val->getType());
395 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
397 NameSet::iterator NI = UsedNames.find(name);
398 if (NI != UsedNames.end())
399 name += std::string("_") + utostr(uniqueNum++);
400 UsedNames.insert(name);
401 return ValueNames[val] = name;
405 CppWriter::printCppName(const Value* val) {
406 printEscapedString(getCppName(val));
410 CppWriter::printTypeInternal(const Type* Ty) {
411 // We don't print definitions for primitive types
412 if (Ty->isPrimitiveType() || Ty->isInteger())
415 // If we already defined this type, we don't need to define it again.
416 if (DefinedTypes.find(Ty) != DefinedTypes.end())
419 // Everything below needs the name for the type so get it now.
420 std::string typeName(getCppName(Ty));
422 // Search the type stack for recursion. If we find it, then generate this
423 // as an OpaqueType, but make sure not to do this multiple times because
424 // the type could appear in multiple places on the stack. Once the opaque
425 // definition is issued, it must not be re-issued. Consequently we have to
426 // check the UnresolvedTypes list as well.
427 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
428 if (TI != TypeStack.end()) {
429 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
430 if (I == UnresolvedTypes.end()) {
431 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
433 UnresolvedTypes[Ty] = typeName;
438 // We're going to print a derived type which, by definition, contains other
439 // types. So, push this one we're printing onto the type stack to assist with
440 // recursive definitions.
441 TypeStack.push_back(Ty);
443 // Print the type definition
444 switch (Ty->getTypeID()) {
445 case Type::FunctionTyID: {
446 const FunctionType* FT = cast<FunctionType>(Ty);
447 Out << "std::vector<const Type*>" << typeName << "_args;";
449 FunctionType::param_iterator PI = FT->param_begin();
450 FunctionType::param_iterator PE = FT->param_end();
451 for (; PI != PE; ++PI) {
452 const Type* argTy = static_cast<const Type*>(*PI);
453 bool isForward = printTypeInternal(argTy);
454 std::string argName(getCppName(argTy));
455 Out << typeName << "_args.push_back(" << argName;
461 const ParamAttrsList *PAL = FT->getParamAttrs();
462 Out << "ParamAttrsList *" << typeName << "_PAL = 0;";
464 if (PAL && !PAL->empty()) {
465 Out << typeName << "_PAL = new ParamAttrsList();";
467 for (unsigned i = 0; i < PAL->size(); ++i) {
468 uint16_t index = PAL->getParamIndex(i);
469 uint16_t attrs = PAL->getParamAttrs(index);
470 Out << typeName << "_PAL->addAttributes(" << index << ", 0";
471 if (attrs & ParamAttr::SExt)
472 Out << " | ParamAttr::SExt";
473 if (attrs & ParamAttr::ZExt)
474 Out << " | ParamAttr::ZExt";
475 if (attrs & ParamAttr::StructRet)
476 Out << " | ParamAttr::StructRet";
477 if (attrs & ParamAttr::InReg)
478 Out << " | ParamAttr::InReg";
479 if (attrs & ParamAttr::NoReturn)
480 Out << " | ParamAttr::NoReturn";
481 if (attrs & ParamAttr::NoUnwind)
482 Out << " | ParamAttr::NoUnwind";
487 bool isForward = printTypeInternal(FT->getReturnType());
488 std::string retTypeName(getCppName(FT->getReturnType()));
489 Out << "FunctionType* " << typeName << " = FunctionType::get(";
490 in(); nl(Out) << "/*Result=*/" << retTypeName;
494 nl(Out) << "/*Params=*/" << typeName << "_args,";
495 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true," : "false,") ;
496 nl(Out) << "/*ParamAttrs=*/" << typeName << "_PAL" << ");";
501 case Type::StructTyID: {
502 const StructType* ST = cast<StructType>(Ty);
503 Out << "std::vector<const Type*>" << typeName << "_fields;";
505 StructType::element_iterator EI = ST->element_begin();
506 StructType::element_iterator EE = ST->element_end();
507 for (; EI != EE; ++EI) {
508 const Type* fieldTy = static_cast<const Type*>(*EI);
509 bool isForward = printTypeInternal(fieldTy);
510 std::string fieldName(getCppName(fieldTy));
511 Out << typeName << "_fields.push_back(" << fieldName;
517 Out << "StructType* " << typeName << " = StructType::get("
518 << typeName << "_fields);";
522 case Type::ArrayTyID: {
523 const ArrayType* AT = cast<ArrayType>(Ty);
524 const Type* ET = AT->getElementType();
525 bool isForward = printTypeInternal(ET);
526 std::string elemName(getCppName(ET));
527 Out << "ArrayType* " << typeName << " = ArrayType::get("
528 << elemName << (isForward ? "_fwd" : "")
529 << ", " << utostr(AT->getNumElements()) << ");";
533 case Type::PointerTyID: {
534 const PointerType* PT = cast<PointerType>(Ty);
535 const Type* ET = PT->getElementType();
536 bool isForward = printTypeInternal(ET);
537 std::string elemName(getCppName(ET));
538 Out << "PointerType* " << typeName << " = PointerType::get("
539 << elemName << (isForward ? "_fwd" : "") << ");";
543 case Type::VectorTyID: {
544 const VectorType* PT = cast<VectorType>(Ty);
545 const Type* ET = PT->getElementType();
546 bool isForward = printTypeInternal(ET);
547 std::string elemName(getCppName(ET));
548 Out << "VectorType* " << typeName << " = VectorType::get("
549 << elemName << (isForward ? "_fwd" : "")
550 << ", " << utostr(PT->getNumElements()) << ");";
554 case Type::OpaqueTyID: {
555 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
560 error("Invalid TypeID");
563 // If the type had a name, make sure we recreate it.
564 const std::string* progTypeName =
565 findTypeName(TheModule->getTypeSymbolTable(),Ty);
567 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
572 // Pop us off the type stack
573 TypeStack.pop_back();
575 // Indicate that this type is now defined.
576 DefinedTypes.insert(Ty);
578 // Early resolve as many unresolved types as possible. Search the unresolved
579 // types map for the type we just printed. Now that its definition is complete
580 // we can resolve any previous references to it. This prevents a cascade of
582 TypeMap::iterator I = UnresolvedTypes.find(Ty);
583 if (I != UnresolvedTypes.end()) {
584 Out << "cast<OpaqueType>(" << I->second
585 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
587 Out << I->second << " = cast<";
588 switch (Ty->getTypeID()) {
589 case Type::FunctionTyID: Out << "FunctionType"; break;
590 case Type::ArrayTyID: Out << "ArrayType"; break;
591 case Type::StructTyID: Out << "StructType"; break;
592 case Type::VectorTyID: Out << "VectorType"; break;
593 case Type::PointerTyID: Out << "PointerType"; break;
594 case Type::OpaqueTyID: Out << "OpaqueType"; break;
595 default: Out << "NoSuchDerivedType"; break;
597 Out << ">(" << I->second << "_fwd.get());";
599 UnresolvedTypes.erase(I);
602 // Finally, separate the type definition from other with a newline.
605 // We weren't a recursive type
609 // Prints a type definition. Returns true if it could not resolve all the types
610 // in the definition but had to use a forward reference.
612 CppWriter::printType(const Type* Ty) {
613 assert(TypeStack.empty());
615 printTypeInternal(Ty);
616 assert(TypeStack.empty());
620 CppWriter::printTypes(const Module* M) {
622 // Walk the symbol table and print out all its types
623 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
624 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
627 // For primitive types and types already defined, just add a name
628 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
629 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
630 TNI != TypeNames.end()) {
631 Out << "mod->addTypeName(\"";
632 printEscapedString(TI->first);
633 Out << "\", " << getCppName(TI->second) << ");";
635 // For everything else, define the type
637 printType(TI->second);
641 // Add all of the global variables to the value table...
642 for (Module::const_global_iterator I = TheModule->global_begin(),
643 E = TheModule->global_end(); I != E; ++I) {
644 if (I->hasInitializer())
645 printType(I->getInitializer()->getType());
646 printType(I->getType());
649 // Add all the functions to the table
650 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
652 printType(FI->getReturnType());
653 printType(FI->getFunctionType());
654 // Add all the function arguments
655 for(Function::const_arg_iterator AI = FI->arg_begin(),
656 AE = FI->arg_end(); AI != AE; ++AI) {
657 printType(AI->getType());
660 // Add all of the basic blocks and instructions
661 for (Function::const_iterator BB = FI->begin(),
662 E = FI->end(); BB != E; ++BB) {
663 printType(BB->getType());
664 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
666 printType(I->getType());
667 for (unsigned i = 0; i < I->getNumOperands(); ++i)
668 printType(I->getOperand(i)->getType());
675 // printConstant - Print out a constant pool entry...
676 void CppWriter::printConstant(const Constant *CV) {
677 // First, if the constant is actually a GlobalValue (variable or function) or
678 // its already in the constant list then we've printed it already and we can
680 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
683 std::string constName(getCppName(CV));
684 std::string typeName(getCppName(CV->getType()));
685 if (CV->isNullValue()) {
686 Out << "Constant* " << constName << " = Constant::getNullValue("
691 if (isa<GlobalValue>(CV)) {
692 // Skip variables and functions, we emit them elsewhere
695 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
696 Out << "ConstantInt* " << constName << " = ConstantInt::get("
697 << "APInt(cast<IntegerType>(" << typeName << ")->getBitWidth(),"
698 << " \"" << CI->getValue().toStringSigned(10) << "\", 10));";
699 } else if (isa<ConstantAggregateZero>(CV)) {
700 Out << "ConstantAggregateZero* " << constName
701 << " = ConstantAggregateZero::get(" << typeName << ");";
702 } else if (isa<ConstantPointerNull>(CV)) {
703 Out << "ConstantPointerNull* " << constName
704 << " = ConstanPointerNull::get(" << typeName << ");";
705 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
706 Out << "ConstantFP* " << constName << " = ";
709 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
710 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
711 Out << "Constant* " << constName << " = ConstantArray::get(\"";
712 printEscapedString(CA->getAsString());
713 // Determine if we want null termination or not.
714 if (CA->getType()->getNumElements() <= CA->getAsString().length())
715 Out << "\", false";// No null terminator
717 Out << "\", true"; // Indicate that the null terminator should be added.
720 Out << "std::vector<Constant*> " << constName << "_elems;";
722 unsigned N = CA->getNumOperands();
723 for (unsigned i = 0; i < N; ++i) {
724 printConstant(CA->getOperand(i)); // recurse to print operands
725 Out << constName << "_elems.push_back("
726 << getCppName(CA->getOperand(i)) << ");";
729 Out << "Constant* " << constName << " = ConstantArray::get("
730 << typeName << ", " << constName << "_elems);";
732 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
733 Out << "std::vector<Constant*> " << constName << "_fields;";
735 unsigned N = CS->getNumOperands();
736 for (unsigned i = 0; i < N; i++) {
737 printConstant(CS->getOperand(i));
738 Out << constName << "_fields.push_back("
739 << getCppName(CS->getOperand(i)) << ");";
742 Out << "Constant* " << constName << " = ConstantStruct::get("
743 << typeName << ", " << constName << "_fields);";
744 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
745 Out << "std::vector<Constant*> " << constName << "_elems;";
747 unsigned N = CP->getNumOperands();
748 for (unsigned i = 0; i < N; ++i) {
749 printConstant(CP->getOperand(i));
750 Out << constName << "_elems.push_back("
751 << getCppName(CP->getOperand(i)) << ");";
754 Out << "Constant* " << constName << " = ConstantVector::get("
755 << typeName << ", " << constName << "_elems);";
756 } else if (isa<UndefValue>(CV)) {
757 Out << "UndefValue* " << constName << " = UndefValue::get("
759 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
760 if (CE->getOpcode() == Instruction::GetElementPtr) {
761 Out << "std::vector<Constant*> " << constName << "_indices;";
763 printConstant(CE->getOperand(0));
764 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
765 printConstant(CE->getOperand(i));
766 Out << constName << "_indices.push_back("
767 << getCppName(CE->getOperand(i)) << ");";
770 Out << "Constant* " << constName
771 << " = ConstantExpr::getGetElementPtr("
772 << getCppName(CE->getOperand(0)) << ", "
773 << "&" << constName << "_indices[0], " << CE->getNumOperands() - 1
775 } else if (CE->isCast()) {
776 printConstant(CE->getOperand(0));
777 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
778 switch (CE->getOpcode()) {
779 default: assert(0 && "Invalid cast opcode");
780 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
781 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
782 case Instruction::SExt: Out << "Instruction::SExt"; break;
783 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
784 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
785 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
786 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
787 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
788 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
789 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
790 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
791 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
793 Out << ", " << getCppName(CE->getOperand(0)) << ", "
794 << getCppName(CE->getType()) << ");";
796 unsigned N = CE->getNumOperands();
797 for (unsigned i = 0; i < N; ++i ) {
798 printConstant(CE->getOperand(i));
800 Out << "Constant* " << constName << " = ConstantExpr::";
801 switch (CE->getOpcode()) {
802 case Instruction::Add: Out << "getAdd("; break;
803 case Instruction::Sub: Out << "getSub("; break;
804 case Instruction::Mul: Out << "getMul("; break;
805 case Instruction::UDiv: Out << "getUDiv("; break;
806 case Instruction::SDiv: Out << "getSDiv("; break;
807 case Instruction::FDiv: Out << "getFDiv("; break;
808 case Instruction::URem: Out << "getURem("; break;
809 case Instruction::SRem: Out << "getSRem("; break;
810 case Instruction::FRem: Out << "getFRem("; break;
811 case Instruction::And: Out << "getAnd("; break;
812 case Instruction::Or: Out << "getOr("; break;
813 case Instruction::Xor: Out << "getXor("; break;
814 case Instruction::ICmp:
815 Out << "getICmp(ICmpInst::ICMP_";
816 switch (CE->getPredicate()) {
817 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
818 case ICmpInst::ICMP_NE: Out << "NE"; break;
819 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
820 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
821 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
822 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
823 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
824 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
825 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
826 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
827 default: error("Invalid ICmp Predicate");
830 case Instruction::FCmp:
831 Out << "getFCmp(FCmpInst::FCMP_";
832 switch (CE->getPredicate()) {
833 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
834 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
835 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
836 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
837 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
838 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
839 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
840 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
841 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
842 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
843 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
844 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
845 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
846 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
847 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
848 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
849 default: error("Invalid FCmp Predicate");
852 case Instruction::Shl: Out << "getShl("; break;
853 case Instruction::LShr: Out << "getLShr("; break;
854 case Instruction::AShr: Out << "getAShr("; break;
855 case Instruction::Select: Out << "getSelect("; break;
856 case Instruction::ExtractElement: Out << "getExtractElement("; break;
857 case Instruction::InsertElement: Out << "getInsertElement("; break;
858 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
860 error("Invalid constant expression");
863 Out << getCppName(CE->getOperand(0));
864 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
865 Out << ", " << getCppName(CE->getOperand(i));
869 error("Bad Constant");
870 Out << "Constant* " << constName << " = 0; ";
876 CppWriter::printConstants(const Module* M) {
877 // Traverse all the global variables looking for constant initializers
878 for (Module::const_global_iterator I = TheModule->global_begin(),
879 E = TheModule->global_end(); I != E; ++I)
880 if (I->hasInitializer())
881 printConstant(I->getInitializer());
883 // Traverse the LLVM functions looking for constants
884 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
886 // Add all of the basic blocks and instructions
887 for (Function::const_iterator BB = FI->begin(),
888 E = FI->end(); BB != E; ++BB) {
889 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
891 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
892 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
901 void CppWriter::printVariableUses(const GlobalVariable *GV) {
902 nl(Out) << "// Type Definitions";
904 printType(GV->getType());
905 if (GV->hasInitializer()) {
906 Constant* Init = GV->getInitializer();
907 printType(Init->getType());
908 if (Function* F = dyn_cast<Function>(Init)) {
909 nl(Out)<< "/ Function Declarations"; nl(Out);
910 printFunctionHead(F);
911 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
912 nl(Out) << "// Global Variable Declarations"; nl(Out);
913 printVariableHead(gv);
915 nl(Out) << "// Constant Definitions"; nl(Out);
918 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
919 nl(Out) << "// Global Variable Definitions"; nl(Out);
920 printVariableBody(gv);
925 void CppWriter::printVariableHead(const GlobalVariable *GV) {
926 nl(Out) << "GlobalVariable* " << getCppName(GV);
928 Out << " = mod->getGlobalVariable(";
929 printEscapedString(GV->getName());
930 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
931 nl(Out) << "if (!" << getCppName(GV) << ") {";
932 in(); nl(Out) << getCppName(GV);
934 Out << " = new GlobalVariable(";
935 nl(Out) << "/*Type=*/";
936 printCppName(GV->getType()->getElementType());
938 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
940 nl(Out) << "/*Linkage=*/";
941 printLinkageType(GV->getLinkage());
943 nl(Out) << "/*Initializer=*/0, ";
944 if (GV->hasInitializer()) {
945 Out << "// has initializer, specified below";
947 nl(Out) << "/*Name=*/\"";
948 printEscapedString(GV->getName());
953 if (GV->hasSection()) {
955 Out << "->setSection(\"";
956 printEscapedString(GV->getSection());
960 if (GV->getAlignment()) {
962 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
966 out(); Out << "}"; nl(Out);
971 CppWriter::printVariableBody(const GlobalVariable *GV) {
972 if (GV->hasInitializer()) {
974 Out << "->setInitializer(";
975 //if (!isa<GlobalValue(GV->getInitializer()))
977 Out << getCppName(GV->getInitializer()) << ");";
983 CppWriter::getOpName(Value* V) {
984 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
985 return getCppName(V);
987 // See if its alread in the map of forward references, if so just return the
988 // name we already set up for it
989 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
990 if (I != ForwardRefs.end())
993 // This is a new forward reference. Generate a unique name for it
994 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
996 // Yes, this is a hack. An Argument is the smallest instantiable value that
997 // we can make as a placeholder for the real value. We'll replace these
998 // Argument instances later.
999 Out << "Argument* " << result << " = new Argument("
1000 << getCppName(V->getType()) << ");";
1002 ForwardRefs[V] = result;
1006 // printInstruction - This member is called for each Instruction in a function.
1008 CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
1009 std::string iName(getCppName(I));
1011 // Before we emit this instruction, we need to take care of generating any
1012 // forward references. So, we get the names of all the operands in advance
1013 std::string* opNames = new std::string[I->getNumOperands()];
1014 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1015 opNames[i] = getOpName(I->getOperand(i));
1018 switch (I->getOpcode()) {
1019 case Instruction::Ret: {
1020 const ReturnInst* ret = cast<ReturnInst>(I);
1021 Out << "new ReturnInst("
1022 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1025 case Instruction::Br: {
1026 const BranchInst* br = cast<BranchInst>(I);
1027 Out << "new BranchInst(" ;
1028 if (br->getNumOperands() == 3 ) {
1029 Out << opNames[0] << ", "
1030 << opNames[1] << ", "
1031 << opNames[2] << ", ";
1033 } else if (br->getNumOperands() == 1) {
1034 Out << opNames[0] << ", ";
1036 error("Branch with 2 operands?");
1038 Out << bbname << ");";
1041 case Instruction::Switch: {
1042 const SwitchInst* sw = cast<SwitchInst>(I);
1043 Out << "SwitchInst* " << iName << " = new SwitchInst("
1044 << opNames[0] << ", "
1045 << opNames[1] << ", "
1046 << sw->getNumCases() << ", " << bbname << ");";
1048 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1049 Out << iName << "->addCase("
1050 << opNames[i] << ", "
1051 << opNames[i+1] << ");";
1056 case Instruction::Invoke: {
1057 const InvokeInst* inv = cast<InvokeInst>(I);
1058 Out << "std::vector<Value*> " << iName << "_params;";
1060 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1061 Out << iName << "_params.push_back("
1062 << opNames[i] << ");";
1065 Out << "InvokeInst *" << iName << " = new InvokeInst("
1066 << opNames[0] << ", "
1067 << opNames[1] << ", "
1068 << opNames[2] << ", "
1069 << "&" << iName << "_params[0], " << inv->getNumOperands() - 3
1071 printEscapedString(inv->getName());
1072 Out << "\", " << bbname << ");";
1073 nl(Out) << iName << "->setCallingConv(";
1074 printCallingConv(inv->getCallingConv());
1078 case Instruction::Unwind: {
1079 Out << "new UnwindInst("
1083 case Instruction::Unreachable:{
1084 Out << "new UnreachableInst("
1088 case Instruction::Add:
1089 case Instruction::Sub:
1090 case Instruction::Mul:
1091 case Instruction::UDiv:
1092 case Instruction::SDiv:
1093 case Instruction::FDiv:
1094 case Instruction::URem:
1095 case Instruction::SRem:
1096 case Instruction::FRem:
1097 case Instruction::And:
1098 case Instruction::Or:
1099 case Instruction::Xor:
1100 case Instruction::Shl:
1101 case Instruction::LShr:
1102 case Instruction::AShr:{
1103 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1104 switch (I->getOpcode()) {
1105 case Instruction::Add: Out << "Instruction::Add"; break;
1106 case Instruction::Sub: Out << "Instruction::Sub"; break;
1107 case Instruction::Mul: Out << "Instruction::Mul"; break;
1108 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1109 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1110 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1111 case Instruction::URem:Out << "Instruction::URem"; break;
1112 case Instruction::SRem:Out << "Instruction::SRem"; break;
1113 case Instruction::FRem:Out << "Instruction::FRem"; break;
1114 case Instruction::And: Out << "Instruction::And"; break;
1115 case Instruction::Or: Out << "Instruction::Or"; break;
1116 case Instruction::Xor: Out << "Instruction::Xor"; break;
1117 case Instruction::Shl: Out << "Instruction::Shl"; break;
1118 case Instruction::LShr:Out << "Instruction::LShr"; break;
1119 case Instruction::AShr:Out << "Instruction::AShr"; break;
1120 default: Out << "Instruction::BadOpCode"; break;
1122 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1123 printEscapedString(I->getName());
1124 Out << "\", " << bbname << ");";
1127 case Instruction::FCmp: {
1128 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1129 switch (cast<FCmpInst>(I)->getPredicate()) {
1130 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1131 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1132 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1133 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1134 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1135 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1136 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1137 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1138 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1139 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1140 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1141 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1142 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1143 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1144 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1145 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1146 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1148 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1149 printEscapedString(I->getName());
1150 Out << "\", " << bbname << ");";
1153 case Instruction::ICmp: {
1154 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1155 switch (cast<ICmpInst>(I)->getPredicate()) {
1156 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1157 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1158 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1159 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1160 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1161 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1162 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1163 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1164 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1165 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1166 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1168 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1169 printEscapedString(I->getName());
1170 Out << "\", " << bbname << ");";
1173 case Instruction::Malloc: {
1174 const MallocInst* mallocI = cast<MallocInst>(I);
1175 Out << "MallocInst* " << iName << " = new MallocInst("
1176 << getCppName(mallocI->getAllocatedType()) << ", ";
1177 if (mallocI->isArrayAllocation())
1178 Out << opNames[0] << ", " ;
1180 printEscapedString(mallocI->getName());
1181 Out << "\", " << bbname << ");";
1182 if (mallocI->getAlignment())
1183 nl(Out) << iName << "->setAlignment("
1184 << mallocI->getAlignment() << ");";
1187 case Instruction::Free: {
1188 Out << "FreeInst* " << iName << " = new FreeInst("
1189 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1192 case Instruction::Alloca: {
1193 const AllocaInst* allocaI = cast<AllocaInst>(I);
1194 Out << "AllocaInst* " << iName << " = new AllocaInst("
1195 << getCppName(allocaI->getAllocatedType()) << ", ";
1196 if (allocaI->isArrayAllocation())
1197 Out << opNames[0] << ", ";
1199 printEscapedString(allocaI->getName());
1200 Out << "\", " << bbname << ");";
1201 if (allocaI->getAlignment())
1202 nl(Out) << iName << "->setAlignment("
1203 << allocaI->getAlignment() << ");";
1206 case Instruction::Load:{
1207 const LoadInst* load = cast<LoadInst>(I);
1208 Out << "LoadInst* " << iName << " = new LoadInst("
1209 << opNames[0] << ", \"";
1210 printEscapedString(load->getName());
1211 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1212 << ", " << bbname << ");";
1215 case Instruction::Store: {
1216 const StoreInst* store = cast<StoreInst>(I);
1217 Out << "StoreInst* " << iName << " = new StoreInst("
1218 << opNames[0] << ", "
1219 << opNames[1] << ", "
1220 << (store->isVolatile() ? "true" : "false")
1221 << ", " << bbname << ");";
1224 case Instruction::GetElementPtr: {
1225 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1226 if (gep->getNumOperands() <= 2) {
1227 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1229 if (gep->getNumOperands() == 2)
1230 Out << ", " << opNames[1];
1232 Out << "std::vector<Value*> " << iName << "_indices;";
1234 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1235 Out << iName << "_indices.push_back("
1236 << opNames[i] << ");";
1239 Out << "Instruction* " << iName << " = new GetElementPtrInst("
1240 << opNames[0] << ", &" << iName << "_indices[0], "
1241 << gep->getNumOperands() - 1;
1244 printEscapedString(gep->getName());
1245 Out << "\", " << bbname << ");";
1248 case Instruction::PHI: {
1249 const PHINode* phi = cast<PHINode>(I);
1251 Out << "PHINode* " << iName << " = new PHINode("
1252 << getCppName(phi->getType()) << ", \"";
1253 printEscapedString(phi->getName());
1254 Out << "\", " << bbname << ");";
1255 nl(Out) << iName << "->reserveOperandSpace("
1256 << phi->getNumIncomingValues()
1259 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1260 Out << iName << "->addIncoming("
1261 << opNames[i] << ", " << opNames[i+1] << ");";
1266 case Instruction::Trunc:
1267 case Instruction::ZExt:
1268 case Instruction::SExt:
1269 case Instruction::FPTrunc:
1270 case Instruction::FPExt:
1271 case Instruction::FPToUI:
1272 case Instruction::FPToSI:
1273 case Instruction::UIToFP:
1274 case Instruction::SIToFP:
1275 case Instruction::PtrToInt:
1276 case Instruction::IntToPtr:
1277 case Instruction::BitCast: {
1278 const CastInst* cst = cast<CastInst>(I);
1279 Out << "CastInst* " << iName << " = new ";
1280 switch (I->getOpcode()) {
1281 case Instruction::Trunc: Out << "TruncInst"; break;
1282 case Instruction::ZExt: Out << "ZExtInst"; break;
1283 case Instruction::SExt: Out << "SExtInst"; break;
1284 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1285 case Instruction::FPExt: Out << "FPExtInst"; break;
1286 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1287 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1288 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1289 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1290 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1291 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1292 case Instruction::BitCast: Out << "BitCastInst"; break;
1293 default: assert(!"Unreachable"); break;
1295 Out << "(" << opNames[0] << ", "
1296 << getCppName(cst->getType()) << ", \"";
1297 printEscapedString(cst->getName());
1298 Out << "\", " << bbname << ");";
1301 case Instruction::Call:{
1302 const CallInst* call = cast<CallInst>(I);
1303 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1304 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1305 << getCppName(ila->getFunctionType()) << ", \""
1306 << ila->getAsmString() << "\", \""
1307 << ila->getConstraintString() << "\","
1308 << (ila->hasSideEffects() ? "true" : "false") << ");";
1311 if (call->getNumOperands() > 3) {
1312 Out << "std::vector<Value*> " << iName << "_params;";
1314 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1315 Out << iName << "_params.push_back(" << opNames[i] << ");";
1318 Out << "CallInst* " << iName << " = new CallInst("
1319 << opNames[0] << ", &" << iName << "_params[0], "
1320 << call->getNumOperands() - 1 << ", \"";
1321 } else if (call->getNumOperands() == 3) {
1322 Out << "CallInst* " << iName << " = new CallInst("
1323 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1324 } else if (call->getNumOperands() == 2) {
1325 Out << "CallInst* " << iName << " = new CallInst("
1326 << opNames[0] << ", " << opNames[1] << ", \"";
1328 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
1331 printEscapedString(call->getName());
1332 Out << "\", " << bbname << ");";
1333 nl(Out) << iName << "->setCallingConv(";
1334 printCallingConv(call->getCallingConv());
1336 nl(Out) << iName << "->setTailCall("
1337 << (call->isTailCall() ? "true":"false");
1341 case Instruction::Select: {
1342 const SelectInst* sel = cast<SelectInst>(I);
1343 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
1344 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1345 printEscapedString(sel->getName());
1346 Out << "\", " << bbname << ");";
1349 case Instruction::UserOp1:
1351 case Instruction::UserOp2: {
1352 /// FIXME: What should be done here?
1355 case Instruction::VAArg: {
1356 const VAArgInst* va = cast<VAArgInst>(I);
1357 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1358 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1359 printEscapedString(va->getName());
1360 Out << "\", " << bbname << ");";
1363 case Instruction::ExtractElement: {
1364 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1365 Out << "ExtractElementInst* " << getCppName(eei)
1366 << " = new ExtractElementInst(" << opNames[0]
1367 << ", " << opNames[1] << ", \"";
1368 printEscapedString(eei->getName());
1369 Out << "\", " << bbname << ");";
1372 case Instruction::InsertElement: {
1373 const InsertElementInst* iei = cast<InsertElementInst>(I);
1374 Out << "InsertElementInst* " << getCppName(iei)
1375 << " = new InsertElementInst(" << opNames[0]
1376 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1377 printEscapedString(iei->getName());
1378 Out << "\", " << bbname << ");";
1381 case Instruction::ShuffleVector: {
1382 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1383 Out << "ShuffleVectorInst* " << getCppName(svi)
1384 << " = new ShuffleVectorInst(" << opNames[0]
1385 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1386 printEscapedString(svi->getName());
1387 Out << "\", " << bbname << ");";
1391 DefinedValues.insert(I);
1396 // Print out the types, constants and declarations needed by one function
1397 void CppWriter::printFunctionUses(const Function* F) {
1399 nl(Out) << "// Type Definitions"; nl(Out);
1401 // Print the function's return type
1402 printType(F->getReturnType());
1404 // Print the function's function type
1405 printType(F->getFunctionType());
1407 // Print the types of each of the function's arguments
1408 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1410 printType(AI->getType());
1414 // Print type definitions for every type referenced by an instruction and
1415 // make a note of any global values or constants that are referenced
1416 std::vector<GlobalValue*> gvs;
1417 std::vector<Constant*> consts;
1418 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1419 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1421 // Print the type of the instruction itself
1422 printType(I->getType());
1424 // Print the type of each of the instruction's operands
1425 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1426 Value* operand = I->getOperand(i);
1427 printType(operand->getType());
1428 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1430 else if (Constant* C = dyn_cast<Constant>(operand))
1431 consts.push_back(C);
1436 // Print the function declarations for any functions encountered
1437 nl(Out) << "// Function Declarations"; nl(Out);
1438 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1440 if (Function* Fun = dyn_cast<Function>(*I)) {
1441 if (!is_inline || Fun != F)
1442 printFunctionHead(Fun);
1446 // Print the global variable declarations for any variables encountered
1447 nl(Out) << "// Global Variable Declarations"; nl(Out);
1448 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1450 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1451 printVariableHead(F);
1454 // Print the constants found
1455 nl(Out) << "// Constant Definitions"; nl(Out);
1456 for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1461 // Process the global variables definitions now that all the constants have
1462 // been emitted. These definitions just couple the gvars with their constant
1464 nl(Out) << "// Global Variable Definitions"; nl(Out);
1465 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1467 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1468 printVariableBody(GV);
1472 void CppWriter::printFunctionHead(const Function* F) {
1473 nl(Out) << "Function* " << getCppName(F);
1475 Out << " = mod->getFunction(\"";
1476 printEscapedString(F->getName());
1477 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1478 nl(Out) << "if (!" << getCppName(F) << ") {";
1479 nl(Out) << getCppName(F);
1481 Out<< " = new Function(";
1482 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1483 nl(Out) << "/*Linkage=*/";
1484 printLinkageType(F->getLinkage());
1486 nl(Out) << "/*Name=*/\"";
1487 printEscapedString(F->getName());
1488 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1491 Out << "->setCallingConv(";
1492 printCallingConv(F->getCallingConv());
1495 if (F->hasSection()) {
1497 Out << "->setSection(\"" << F->getSection() << "\");";
1500 if (F->getAlignment()) {
1502 Out << "->setAlignment(" << F->getAlignment() << ");";
1511 void CppWriter::printFunctionBody(const Function *F) {
1512 if (F->isDeclaration())
1513 return; // external functions have no bodies.
1515 // Clear the DefinedValues and ForwardRefs maps because we can't have
1516 // cross-function forward refs
1517 ForwardRefs.clear();
1518 DefinedValues.clear();
1520 // Create all the argument values
1522 if (!F->arg_empty()) {
1523 Out << "Function::arg_iterator args = " << getCppName(F)
1524 << "->arg_begin();";
1527 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1529 Out << "Value* " << getCppName(AI) << " = args++;";
1531 if (AI->hasName()) {
1532 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1538 // Create all the basic blocks
1540 for (Function::const_iterator BI = F->begin(), BE = F->end();
1542 std::string bbname(getCppName(BI));
1543 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
1545 printEscapedString(BI->getName());
1546 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1550 // Output all of its basic blocks... for the function
1551 for (Function::const_iterator BI = F->begin(), BE = F->end();
1553 std::string bbname(getCppName(BI));
1554 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1557 // Output all of the instructions in the basic block...
1558 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1560 printInstruction(I,bbname);
1564 // Loop over the ForwardRefs and resolve them now that all instructions
1566 if (!ForwardRefs.empty()) {
1567 nl(Out) << "// Resolve Forward References";
1571 while (!ForwardRefs.empty()) {
1572 ForwardRefMap::iterator I = ForwardRefs.begin();
1573 Out << I->second << "->replaceAllUsesWith("
1574 << getCppName(I->first) << "); delete " << I->second << ";";
1576 ForwardRefs.erase(I);
1580 void CppWriter::printInline(const std::string& fname, const std::string& func) {
1581 const Function* F = TheModule->getFunction(func);
1583 error(std::string("Function '") + func + "' not found in input module");
1586 if (F->isDeclaration()) {
1587 error(std::string("Function '") + func + "' is external!");
1590 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1592 unsigned arg_count = 1;
1593 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1595 Out << ", Value* arg_" << arg_count;
1600 printFunctionUses(F);
1601 printFunctionBody(F);
1603 Out << "return " << getCppName(F->begin()) << ";";
1608 void CppWriter::printModuleBody() {
1609 // Print out all the type definitions
1610 nl(Out) << "// Type Definitions"; nl(Out);
1611 printTypes(TheModule);
1613 // Functions can call each other and global variables can reference them so
1614 // define all the functions first before emitting their function bodies.
1615 nl(Out) << "// Function Declarations"; nl(Out);
1616 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1618 printFunctionHead(I);
1620 // Process the global variables declarations. We can't initialze them until
1621 // after the constants are printed so just print a header for each global
1622 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1623 for (Module::const_global_iterator I = TheModule->global_begin(),
1624 E = TheModule->global_end(); I != E; ++I) {
1625 printVariableHead(I);
1628 // Print out all the constants definitions. Constants don't recurse except
1629 // through GlobalValues. All GlobalValues have been declared at this point
1630 // so we can proceed to generate the constants.
1631 nl(Out) << "// Constant Definitions"; nl(Out);
1632 printConstants(TheModule);
1634 // Process the global variables definitions now that all the constants have
1635 // been emitted. These definitions just couple the gvars with their constant
1637 nl(Out) << "// Global Variable Definitions"; nl(Out);
1638 for (Module::const_global_iterator I = TheModule->global_begin(),
1639 E = TheModule->global_end(); I != E; ++I) {
1640 printVariableBody(I);
1643 // Finally, we can safely put out all of the function bodies.
1644 nl(Out) << "// Function Definitions"; nl(Out);
1645 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1647 if (!I->isDeclaration()) {
1648 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1652 printFunctionBody(I);
1659 void CppWriter::printProgram(
1660 const std::string& fname,
1661 const std::string& mName
1663 Out << "#include <llvm/Module.h>\n";
1664 Out << "#include <llvm/DerivedTypes.h>\n";
1665 Out << "#include <llvm/Constants.h>\n";
1666 Out << "#include <llvm/GlobalVariable.h>\n";
1667 Out << "#include <llvm/Function.h>\n";
1668 Out << "#include <llvm/CallingConv.h>\n";
1669 Out << "#include <llvm/BasicBlock.h>\n";
1670 Out << "#include <llvm/Instructions.h>\n";
1671 Out << "#include <llvm/InlineAsm.h>\n";
1672 Out << "#include <llvm/ParameterAttributes.h>\n";
1673 Out << "#include <llvm/Support/MathExtras.h>\n";
1674 Out << "#include <llvm/Pass.h>\n";
1675 Out << "#include <llvm/PassManager.h>\n";
1676 Out << "#include <llvm/Analysis/Verifier.h>\n";
1677 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1678 Out << "#include <algorithm>\n";
1679 Out << "#include <iostream>\n\n";
1680 Out << "using namespace llvm;\n\n";
1681 Out << "Module* " << fname << "();\n\n";
1682 Out << "int main(int argc, char**argv) {\n";
1683 Out << " Module* Mod = makeLLVMModule();\n";
1684 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1685 Out << " std::cerr.flush();\n";
1686 Out << " std::cout.flush();\n";
1687 Out << " PassManager PM;\n";
1688 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1689 Out << " PM.run(*Mod);\n";
1690 Out << " return 0;\n";
1692 printModule(fname,mName);
1695 void CppWriter::printModule(
1696 const std::string& fname,
1697 const std::string& mName
1699 nl(Out) << "Module* " << fname << "() {";
1700 nl(Out,1) << "// Module Construction";
1701 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1702 if (!TheModule->getTargetTriple().empty()) {
1703 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1705 if (!TheModule->getTargetTriple().empty()) {
1706 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1710 if (!TheModule->getModuleInlineAsm().empty()) {
1711 nl(Out) << "mod->setModuleInlineAsm(\"";
1712 printEscapedString(TheModule->getModuleInlineAsm());
1717 // Loop over the dependent libraries and emit them.
1718 Module::lib_iterator LI = TheModule->lib_begin();
1719 Module::lib_iterator LE = TheModule->lib_end();
1721 Out << "mod->addLibrary(\"" << *LI << "\");";
1726 nl(Out) << "return mod;";
1731 void CppWriter::printContents(
1732 const std::string& fname, // Name of generated function
1733 const std::string& mName // Name of module generated module
1735 Out << "\nModule* " << fname << "(Module *mod) {\n";
1736 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1738 Out << "\nreturn mod;\n";
1742 void CppWriter::printFunction(
1743 const std::string& fname, // Name of generated function
1744 const std::string& funcName // Name of function to generate
1746 const Function* F = TheModule->getFunction(funcName);
1748 error(std::string("Function '") + funcName + "' not found in input module");
1751 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1752 printFunctionUses(F);
1753 printFunctionHead(F);
1754 printFunctionBody(F);
1755 Out << "return " << getCppName(F) << ";\n";
1759 void CppWriter::printVariable(
1760 const std::string& fname, /// Name of generated function
1761 const std::string& varName // Name of variable to generate
1763 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1766 error(std::string("Variable '") + varName + "' not found in input module");
1769 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1770 printVariableUses(GV);
1771 printVariableHead(GV);
1772 printVariableBody(GV);
1773 Out << "return " << getCppName(GV) << ";\n";
1777 void CppWriter::printType(
1778 const std::string& fname, /// Name of generated function
1779 const std::string& typeName // Name of type to generate
1781 const Type* Ty = TheModule->getTypeByName(typeName);
1783 error(std::string("Type '") + typeName + "' not found in input module");
1786 Out << "\nType* " << fname << "(Module *mod) {\n";
1788 Out << "return " << getCppName(Ty) << ";\n";
1792 } // end anonymous llvm
1796 void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1797 // Initialize a CppWriter for us to use
1798 CppWriter W(o, mod);
1801 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1803 // Get the name of the function we're supposed to generate
1804 std::string fname = FuncName.getValue();
1806 // Get the name of the thing we are to generate
1807 std::string tgtname = NameToGenerate.getValue();
1808 if (GenerationType == GenModule ||
1809 GenerationType == GenContents ||
1810 GenerationType == GenProgram) {
1811 if (tgtname == "!bad!") {
1812 if (mod->getModuleIdentifier() == "-")
1813 tgtname = "<stdin>";
1815 tgtname = mod->getModuleIdentifier();
1817 } else if (tgtname == "!bad!") {
1818 W.error("You must use the -for option with -gen-{function,variable,type}");
1821 switch (WhatToGenerate(GenerationType)) {
1824 fname = "makeLLVMModule";
1825 W.printProgram(fname,tgtname);
1829 fname = "makeLLVMModule";
1830 W.printModule(fname,tgtname);
1834 fname = "makeLLVMModuleContents";
1835 W.printContents(fname,tgtname);
1839 fname = "makeLLVMFunction";
1840 W.printFunction(fname,tgtname);
1844 fname = "makeLLVMInline";
1845 W.printInline(fname,tgtname);
1849 fname = "makeLLVMVariable";
1850 W.printVariable(fname,tgtname);
1854 fname = "makeLLVMType";
1855 W.printType(fname,tgtname);
1858 W.error("Invalid generation option");