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/Module.h"
22 #include "llvm/SymbolTable.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Config/config.h"
36 static cl::opt<std::string>
37 FuncName("funcname", cl::desc("Specify the name of the generated function"),
38 cl::value_desc("function name"));
50 static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
51 cl::desc("Choose what kind of output to generate"),
54 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
55 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
56 clEnumValN(GenContents,"gen-contents", "Generate contents of a module"),
57 clEnumValN(GenFunction,"gen-function", "Generate a function definition"),
58 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
59 clEnumValN(GenVariable,"gen-variable", "Generate a variable definition"),
60 clEnumValN(GenType, "gen-type", "Generate a type definition"),
65 static cl::opt<std::string> NameToGenerate("for", cl::Optional,
66 cl::desc("Specify the name of the thing to generate"),
70 typedef std::vector<const Type*> TypeList;
71 typedef std::map<const Type*,std::string> TypeMap;
72 typedef std::map<const Value*,std::string> ValueMap;
73 typedef std::set<std::string> NameSet;
74 typedef std::set<const Type*> TypeSet;
75 typedef std::set<const Value*> ValueSet;
76 typedef std::map<const Value*,std::string> ForwardRefMap;
81 const Module *TheModule;
85 TypeMap UnresolvedTypes;
89 ValueSet DefinedValues;
90 ForwardRefMap ForwardRefs;
94 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
95 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
96 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
98 const Module* getModule() { return TheModule; }
100 void printProgram(const std::string& fname, const std::string& modName );
101 void printModule(const std::string& fname, const std::string& modName );
102 void printContents(const std::string& fname, const std::string& modName );
103 void printFunction(const std::string& fname, const std::string& funcName );
104 void printInline(const std::string& fname, const std::string& funcName );
105 void printVariable(const std::string& fname, const std::string& varName );
106 void printType(const std::string& fname, const std::string& typeName );
108 void error(const std::string& msg);
111 void printLinkageType(GlobalValue::LinkageTypes LT);
112 void printCallingConv(unsigned cc);
113 void printEscapedString(const std::string& str);
114 void printCFP(const ConstantFP* CFP);
116 std::string getCppName(const Type* val);
117 inline void printCppName(const Type* val);
119 std::string getCppName(const Value* val);
120 inline void printCppName(const Value* val);
122 bool printTypeInternal(const Type* Ty);
123 inline void printType(const Type* Ty);
124 void printTypes(const Module* M);
126 void printConstant(const Constant *CPV);
127 void printConstants(const Module* M);
129 void printVariableUses(const GlobalVariable *GV);
130 void printVariableHead(const GlobalVariable *GV);
131 void printVariableBody(const GlobalVariable *GV);
133 void printFunctionUses(const Function *F);
134 void printFunctionHead(const Function *F);
135 void printFunctionBody(const Function *F);
136 void printInstruction(const Instruction *I, const std::string& bbname);
137 std::string getOpName(Value*);
139 void printModuleBody();
143 static unsigned indent_level = 0;
144 inline std::ostream& nl(std::ostream& Out, int delta = 0) {
146 if (delta >= 0 || indent_level >= unsigned(-delta))
147 indent_level += delta;
148 for (unsigned i = 0; i < indent_level; ++i)
153 inline void in() { indent_level++; }
154 inline void out() { if (indent_level >0) indent_level--; }
157 sanitize(std::string& str) {
158 for (size_t i = 0; i < str.length(); ++i)
159 if (!isalnum(str[i]) && str[i] != '_')
164 getTypePrefix(const Type* Ty ) {
166 switch (Ty->getTypeID()) {
167 case Type::VoidTyID: prefix = "void_"; break;
168 case Type::BoolTyID: prefix = "bool_"; break;
169 case Type::Int8TyID: prefix = "int8_"; break;
170 case Type::Int16TyID: prefix = "int16_"; break;
171 case Type::Int32TyID: prefix = "int32_"; break;
172 case Type::Int64TyID: prefix = "int64_"; break;
173 case Type::FloatTyID: prefix = "float_"; break;
174 case Type::DoubleTyID: prefix = "double_"; break;
175 case Type::LabelTyID: prefix = "label_"; break;
176 case Type::FunctionTyID: prefix = "func_"; break;
177 case Type::StructTyID: prefix = "struct_"; break;
178 case Type::ArrayTyID: prefix = "array_"; break;
179 case Type::PointerTyID: prefix = "ptr_"; break;
180 case Type::PackedTyID: prefix = "packed_"; break;
181 case Type::OpaqueTyID: prefix = "opaque_"; break;
182 default: prefix = "other_"; break;
187 // Looks up the type in the symbol table and returns a pointer to its name or
188 // a null pointer if it wasn't found. Note that this isn't the same as the
189 // Mode::getTypeName function which will return an empty string, not a null
190 // pointer if the name is not found.
191 inline const std::string*
192 findTypeName(const SymbolTable& ST, const Type* Ty)
194 SymbolTable::type_const_iterator TI = ST.type_begin();
195 SymbolTable::type_const_iterator TE = ST.type_end();
196 for (;TI != TE; ++TI)
197 if (TI->second == Ty)
203 CppWriter::error(const std::string& msg) {
204 std::cerr << progname << ": " << msg << "\n";
208 // printCFP - Print a floating point constant .. very carefully :)
209 // This makes sure that conversion to/from floating yields the same binary
210 // result so that we don't lose precision.
212 CppWriter::printCFP(const ConstantFP *CFP) {
213 Out << "ConstantFP::get(";
214 if (CFP->getType() == Type::DoubleTy)
215 Out << "Type::DoubleTy, ";
217 Out << "Type::FloatTy, ";
220 sprintf(Buffer, "%A", CFP->getValue());
221 if ((!strncmp(Buffer, "0x", 2) ||
222 !strncmp(Buffer, "-0x", 3) ||
223 !strncmp(Buffer, "+0x", 3)) &&
224 (atof(Buffer) == CFP->getValue()))
225 if (CFP->getType() == Type::DoubleTy)
226 Out << "BitsToDouble(" << Buffer << ")";
228 Out << "BitsToFloat(" << Buffer << ")";
231 std::string StrVal = ftostr(CFP->getValue());
233 while (StrVal[0] == ' ')
234 StrVal.erase(StrVal.begin());
236 // Check to make sure that the stringized number is not some string like
237 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
238 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
239 ((StrVal[0] == '-' || StrVal[0] == '+') &&
240 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
241 (atof(StrVal.c_str()) == CFP->getValue()))
242 if (CFP->getType() == Type::DoubleTy)
246 else if (CFP->getType() == Type::DoubleTy)
247 Out << "BitsToDouble(0x" << std::hex << DoubleToBits(CFP->getValue())
248 << std::dec << "ULL) /* " << StrVal << " */";
250 Out << "BitsToFloat(0x" << std::hex << FloatToBits(CFP->getValue())
251 << std::dec << "U) /* " << StrVal << " */";
259 CppWriter::printCallingConv(unsigned cc){
260 // Print the calling convention.
262 case CallingConv::C: Out << "CallingConv::C"; break;
263 case CallingConv::CSRet: Out << "CallingConv::CSRet"; break;
264 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
265 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
266 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
267 default: Out << cc; break;
272 CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
274 case GlobalValue::InternalLinkage:
275 Out << "GlobalValue::InternalLinkage"; break;
276 case GlobalValue::LinkOnceLinkage:
277 Out << "GlobalValue::LinkOnceLinkage "; break;
278 case GlobalValue::WeakLinkage:
279 Out << "GlobalValue::WeakLinkage"; break;
280 case GlobalValue::AppendingLinkage:
281 Out << "GlobalValue::AppendingLinkage"; break;
282 case GlobalValue::ExternalLinkage:
283 Out << "GlobalValue::ExternalLinkage"; break;
284 case GlobalValue::DLLImportLinkage:
285 Out << "GlobalValue::DllImportLinkage"; break;
286 case GlobalValue::DLLExportLinkage:
287 Out << "GlobalValue::DllExportLinkage"; break;
288 case GlobalValue::ExternalWeakLinkage:
289 Out << "GlobalValue::ExternalWeakLinkage"; break;
290 case GlobalValue::GhostLinkage:
291 Out << "GlobalValue::GhostLinkage"; break;
295 // printEscapedString - Print each character of the specified string, escaping
296 // it if it is not printable or if it is an escape char.
298 CppWriter::printEscapedString(const std::string &Str) {
299 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
300 unsigned char C = Str[i];
301 if (isprint(C) && C != '"' && C != '\\') {
305 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
306 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
312 CppWriter::getCppName(const Type* Ty)
314 // First, handle the primitive types .. easy
315 if (Ty->isPrimitiveType()) {
316 switch (Ty->getTypeID()) {
317 case Type::VoidTyID: return "Type::VoidTy";
318 case Type::BoolTyID: return "Type::BoolTy";
319 case Type::Int8TyID: return "Type::Int8Ty";
320 case Type::Int16TyID: return "Type::Int16Ty";
321 case Type::Int32TyID: return "Type::Int32Ty";
322 case Type::Int64TyID: return "Type::Int64Ty";
323 case Type::FloatTyID: return "Type::FloatTy";
324 case Type::DoubleTyID: return "Type::DoubleTy";
325 case Type::LabelTyID: return "Type::LabelTy";
327 error("Invalid primitive type");
330 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
333 // Now, see if we've seen the type before and return that
334 TypeMap::iterator I = TypeNames.find(Ty);
335 if (I != TypeNames.end())
338 // Okay, let's build a new name for this type. Start with a prefix
339 const char* prefix = 0;
340 switch (Ty->getTypeID()) {
341 case Type::FunctionTyID: prefix = "FuncTy_"; break;
342 case Type::StructTyID: prefix = "StructTy_"; break;
343 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
344 case Type::PointerTyID: prefix = "PointerTy_"; break;
345 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
346 case Type::PackedTyID: prefix = "PackedTy_"; break;
347 default: prefix = "OtherTy_"; break; // prevent breakage
350 // See if the type has a name in the symboltable and build accordingly
351 const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
354 name = std::string(prefix) + *tName;
356 name = std::string(prefix) + utostr(uniqueNum++);
360 return TypeNames[Ty] = name;
364 CppWriter::printCppName(const Type* Ty)
366 printEscapedString(getCppName(Ty));
370 CppWriter::getCppName(const Value* val) {
372 ValueMap::iterator I = ValueNames.find(val);
373 if (I != ValueNames.end() && I->first == val)
376 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
377 name = std::string("gvar_") +
378 getTypePrefix(GV->getType()->getElementType());
379 } else if (isa<Function>(val)) {
380 name = std::string("func_");
381 } else if (const Constant* C = dyn_cast<Constant>(val)) {
382 name = std::string("const_") + getTypePrefix(C->getType());
383 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
385 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
386 Function::const_arg_iterator(Arg)) + 1;
387 name = std::string("arg_") + utostr(argNum);
388 NameSet::iterator NI = UsedNames.find(name);
389 if (NI != UsedNames.end())
390 name += std::string("_") + utostr(uniqueNum++);
391 UsedNames.insert(name);
392 return ValueNames[val] = name;
394 name = getTypePrefix(val->getType());
397 name = getTypePrefix(val->getType());
399 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
401 NameSet::iterator NI = UsedNames.find(name);
402 if (NI != UsedNames.end())
403 name += std::string("_") + utostr(uniqueNum++);
404 UsedNames.insert(name);
405 return ValueNames[val] = name;
409 CppWriter::printCppName(const Value* val) {
410 printEscapedString(getCppName(val));
414 CppWriter::printTypeInternal(const Type* Ty) {
415 // We don't print definitions for primitive types
416 if (Ty->isPrimitiveType())
419 // If we already defined this type, we don't need to define it again.
420 if (DefinedTypes.find(Ty) != DefinedTypes.end())
423 // Everything below needs the name for the type so get it now.
424 std::string typeName(getCppName(Ty));
426 // Search the type stack for recursion. If we find it, then generate this
427 // as an OpaqueType, but make sure not to do this multiple times because
428 // the type could appear in multiple places on the stack. Once the opaque
429 // definition is issued, it must not be re-issued. Consequently we have to
430 // check the UnresolvedTypes list as well.
431 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
432 if (TI != TypeStack.end()) {
433 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
434 if (I == UnresolvedTypes.end()) {
435 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
437 UnresolvedTypes[Ty] = typeName;
442 // We're going to print a derived type which, by definition, contains other
443 // types. So, push this one we're printing onto the type stack to assist with
444 // recursive definitions.
445 TypeStack.push_back(Ty);
447 // Print the type definition
448 switch (Ty->getTypeID()) {
449 case Type::FunctionTyID: {
450 const FunctionType* FT = cast<FunctionType>(Ty);
451 Out << "std::vector<const Type*>" << typeName << "_args;";
453 FunctionType::param_iterator PI = FT->param_begin();
454 FunctionType::param_iterator PE = FT->param_end();
455 for (; PI != PE; ++PI) {
456 const Type* argTy = static_cast<const Type*>(*PI);
457 bool isForward = printTypeInternal(argTy);
458 std::string argName(getCppName(argTy));
459 Out << typeName << "_args.push_back(" << argName;
465 bool isForward = printTypeInternal(FT->getReturnType());
466 std::string retTypeName(getCppName(FT->getReturnType()));
467 Out << "FunctionType* " << typeName << " = FunctionType::get(";
468 in(); nl(Out) << "/*Result=*/" << retTypeName;
472 nl(Out) << "/*Params=*/" << typeName << "_args,";
473 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
478 case Type::StructTyID: {
479 const StructType* ST = cast<StructType>(Ty);
480 Out << "std::vector<const Type*>" << typeName << "_fields;";
482 StructType::element_iterator EI = ST->element_begin();
483 StructType::element_iterator EE = ST->element_end();
484 for (; EI != EE; ++EI) {
485 const Type* fieldTy = static_cast<const Type*>(*EI);
486 bool isForward = printTypeInternal(fieldTy);
487 std::string fieldName(getCppName(fieldTy));
488 Out << typeName << "_fields.push_back(" << fieldName;
494 Out << "StructType* " << typeName << " = StructType::get("
495 << typeName << "_fields);";
499 case Type::ArrayTyID: {
500 const ArrayType* AT = cast<ArrayType>(Ty);
501 const Type* ET = AT->getElementType();
502 bool isForward = printTypeInternal(ET);
503 std::string elemName(getCppName(ET));
504 Out << "ArrayType* " << typeName << " = ArrayType::get("
505 << elemName << (isForward ? "_fwd" : "")
506 << ", " << utostr(AT->getNumElements()) << ");";
510 case Type::PointerTyID: {
511 const PointerType* PT = cast<PointerType>(Ty);
512 const Type* ET = PT->getElementType();
513 bool isForward = printTypeInternal(ET);
514 std::string elemName(getCppName(ET));
515 Out << "PointerType* " << typeName << " = PointerType::get("
516 << elemName << (isForward ? "_fwd" : "") << ");";
520 case Type::PackedTyID: {
521 const PackedType* PT = cast<PackedType>(Ty);
522 const Type* ET = PT->getElementType();
523 bool isForward = printTypeInternal(ET);
524 std::string elemName(getCppName(ET));
525 Out << "PackedType* " << typeName << " = PackedType::get("
526 << elemName << (isForward ? "_fwd" : "")
527 << ", " << utostr(PT->getNumElements()) << ");";
531 case Type::OpaqueTyID: {
532 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
537 error("Invalid TypeID");
540 // If the type had a name, make sure we recreate it.
541 const std::string* progTypeName =
542 findTypeName(TheModule->getSymbolTable(),Ty);
544 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
548 // Pop us off the type stack
549 TypeStack.pop_back();
551 // Indicate that this type is now defined.
552 DefinedTypes.insert(Ty);
554 // Early resolve as many unresolved types as possible. Search the unresolved
555 // types map for the type we just printed. Now that its definition is complete
556 // we can resolve any previous references to it. This prevents a cascade of
558 TypeMap::iterator I = UnresolvedTypes.find(Ty);
559 if (I != UnresolvedTypes.end()) {
560 Out << "cast<OpaqueType>(" << I->second
561 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
563 Out << I->second << " = cast<";
564 switch (Ty->getTypeID()) {
565 case Type::FunctionTyID: Out << "FunctionType"; break;
566 case Type::ArrayTyID: Out << "ArrayType"; break;
567 case Type::StructTyID: Out << "StructType"; break;
568 case Type::PackedTyID: Out << "PackedType"; break;
569 case Type::PointerTyID: Out << "PointerType"; break;
570 case Type::OpaqueTyID: Out << "OpaqueType"; break;
571 default: Out << "NoSuchDerivedType"; break;
573 Out << ">(" << I->second << "_fwd.get());";
575 UnresolvedTypes.erase(I);
578 // Finally, separate the type definition from other with a newline.
581 // We weren't a recursive type
585 // Prints a type definition. Returns true if it could not resolve all the types
586 // in the definition but had to use a forward reference.
588 CppWriter::printType(const Type* Ty) {
589 assert(TypeStack.empty());
591 printTypeInternal(Ty);
592 assert(TypeStack.empty());
596 CppWriter::printTypes(const Module* M) {
598 // Walk the symbol table and print out all its types
599 const SymbolTable& symtab = M->getSymbolTable();
600 for (SymbolTable::type_const_iterator TI = symtab.type_begin(),
601 TE = symtab.type_end(); TI != TE; ++TI) {
603 // For primitive types and types already defined, just add a name
604 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
605 if (TI->second->isPrimitiveType() || TNI != TypeNames.end()) {
606 Out << "mod->addTypeName(\"";
607 printEscapedString(TI->first);
608 Out << "\", " << getCppName(TI->second) << ");";
610 // For everything else, define the type
612 printType(TI->second);
616 // Add all of the global variables to the value table...
617 for (Module::const_global_iterator I = TheModule->global_begin(),
618 E = TheModule->global_end(); I != E; ++I) {
619 if (I->hasInitializer())
620 printType(I->getInitializer()->getType());
621 printType(I->getType());
624 // Add all the functions to the table
625 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
627 printType(FI->getReturnType());
628 printType(FI->getFunctionType());
629 // Add all the function arguments
630 for(Function::const_arg_iterator AI = FI->arg_begin(),
631 AE = FI->arg_end(); AI != AE; ++AI) {
632 printType(AI->getType());
635 // Add all of the basic blocks and instructions
636 for (Function::const_iterator BB = FI->begin(),
637 E = FI->end(); BB != E; ++BB) {
638 printType(BB->getType());
639 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
641 printType(I->getType());
642 for (unsigned i = 0; i < I->getNumOperands(); ++i)
643 printType(I->getOperand(i)->getType());
650 // printConstant - Print out a constant pool entry...
651 void CppWriter::printConstant(const Constant *CV) {
652 // First, if the constant is actually a GlobalValue (variable or function) or
653 // its already in the constant list then we've printed it already and we can
655 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
658 std::string constName(getCppName(CV));
659 std::string typeName(getCppName(CV->getType()));
660 if (CV->isNullValue()) {
661 Out << "Constant* " << constName << " = Constant::getNullValue("
666 if (isa<GlobalValue>(CV)) {
667 // Skip variables and functions, we emit them elsewhere
670 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
671 Out << "ConstantBool* " << constName << " = ConstantBool::get("
672 << (CB->getValue() ? "true" : "false") << ");";
673 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
674 Out << "ConstantInt* " << constName << " = ConstantInt::get("
675 << typeName << ", " << CI->getZExtValue() << ");";
676 } else if (isa<ConstantAggregateZero>(CV)) {
677 Out << "ConstantAggregateZero* " << constName
678 << " = ConstantAggregateZero::get(" << typeName << ");";
679 } else if (isa<ConstantPointerNull>(CV)) {
680 Out << "ConstantPointerNull* " << constName
681 << " = ConstanPointerNull::get(" << typeName << ");";
682 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
683 Out << "ConstantFP* " << constName << " = ";
686 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
687 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
688 Out << "Constant* " << constName << " = ConstantArray::get(\"";
689 printEscapedString(CA->getAsString());
690 // Determine if we want null termination or not.
691 if (CA->getType()->getNumElements() <= CA->getAsString().length())
692 Out << "\", false";// No null terminator
694 Out << "\", true"; // Indicate that the null terminator should be added.
697 Out << "std::vector<Constant*> " << constName << "_elems;";
699 unsigned N = CA->getNumOperands();
700 for (unsigned i = 0; i < N; ++i) {
701 printConstant(CA->getOperand(i)); // recurse to print operands
702 Out << constName << "_elems.push_back("
703 << getCppName(CA->getOperand(i)) << ");";
706 Out << "Constant* " << constName << " = ConstantArray::get("
707 << typeName << ", " << constName << "_elems);";
709 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
710 Out << "std::vector<Constant*> " << constName << "_fields;";
712 unsigned N = CS->getNumOperands();
713 for (unsigned i = 0; i < N; i++) {
714 printConstant(CS->getOperand(i));
715 Out << constName << "_fields.push_back("
716 << getCppName(CS->getOperand(i)) << ");";
719 Out << "Constant* " << constName << " = ConstantStruct::get("
720 << typeName << ", " << constName << "_fields);";
721 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
722 Out << "std::vector<Constant*> " << constName << "_elems;";
724 unsigned N = CP->getNumOperands();
725 for (unsigned i = 0; i < N; ++i) {
726 printConstant(CP->getOperand(i));
727 Out << constName << "_elems.push_back("
728 << getCppName(CP->getOperand(i)) << ");";
731 Out << "Constant* " << constName << " = ConstantPacked::get("
732 << typeName << ", " << constName << "_elems);";
733 } else if (isa<UndefValue>(CV)) {
734 Out << "UndefValue* " << constName << " = UndefValue::get("
736 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
737 if (CE->getOpcode() == Instruction::GetElementPtr) {
738 Out << "std::vector<Constant*> " << constName << "_indices;";
740 printConstant(CE->getOperand(0));
741 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
742 printConstant(CE->getOperand(i));
743 Out << constName << "_indices.push_back("
744 << getCppName(CE->getOperand(i)) << ");";
747 Out << "Constant* " << constName
748 << " = ConstantExpr::getGetElementPtr("
749 << getCppName(CE->getOperand(0)) << ", "
750 << constName << "_indices);";
751 } else if (CE->isCast()) {
752 printConstant(CE->getOperand(0));
753 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
754 switch (CE->getOpcode()) {
755 default: assert(0 && "Invalid cast opcode");
756 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
757 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
758 case Instruction::SExt: Out << "Instruction::SExt"; break;
759 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
760 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
761 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
762 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
763 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
764 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
765 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
766 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
767 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
769 Out << ", " << getCppName(CE->getOperand(0)) << ", "
770 << getCppName(CE->getType()) << ");";
772 unsigned N = CE->getNumOperands();
773 for (unsigned i = 0; i < N; ++i ) {
774 printConstant(CE->getOperand(i));
776 Out << "Constant* " << constName << " = ConstantExpr::";
777 switch (CE->getOpcode()) {
778 case Instruction::Add: Out << "getAdd("; break;
779 case Instruction::Sub: Out << "getSub("; break;
780 case Instruction::Mul: Out << "getMul("; break;
781 case Instruction::UDiv: Out << "getUDiv("; break;
782 case Instruction::SDiv: Out << "getSDiv("; break;
783 case Instruction::FDiv: Out << "getFDiv("; break;
784 case Instruction::URem: Out << "getURem("; break;
785 case Instruction::SRem: Out << "getSRem("; break;
786 case Instruction::FRem: Out << "getFRem("; break;
787 case Instruction::And: Out << "getAnd("; break;
788 case Instruction::Or: Out << "getOr("; break;
789 case Instruction::Xor: Out << "getXor("; break;
790 case Instruction::ICmp:
791 Out << "getICmp(ICmpInst::ICMP_";
792 switch (CE->getPredicate()) {
793 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
794 case ICmpInst::ICMP_NE: Out << "NE"; break;
795 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
796 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
797 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
798 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
799 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
800 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
801 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
802 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
803 default: error("Invalid ICmp Predicate");
806 case Instruction::FCmp:
807 Out << "getFCmp(FCmpInst::FCMP_";
808 switch (CE->getPredicate()) {
809 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
810 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
811 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
812 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
813 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
814 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
815 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
816 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
817 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
818 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
819 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
820 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
821 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
822 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
823 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
824 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
825 default: error("Invalid FCmp Predicate");
828 case Instruction::Shl: Out << "getShl("; break;
829 case Instruction::LShr: Out << "getLShr("; break;
830 case Instruction::AShr: Out << "getAShr("; break;
831 case Instruction::Select: Out << "getSelect("; break;
832 case Instruction::ExtractElement: Out << "getExtractElement("; break;
833 case Instruction::InsertElement: Out << "getInsertElement("; break;
834 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
836 error("Invalid constant expression");
839 Out << getCppName(CE->getOperand(0));
840 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
841 Out << ", " << getCppName(CE->getOperand(i));
845 error("Bad Constant");
846 Out << "Constant* " << constName << " = 0; ";
852 CppWriter::printConstants(const Module* M) {
853 // Traverse all the global variables looking for constant initializers
854 for (Module::const_global_iterator I = TheModule->global_begin(),
855 E = TheModule->global_end(); I != E; ++I)
856 if (I->hasInitializer())
857 printConstant(I->getInitializer());
859 // Traverse the LLVM functions looking for constants
860 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
862 // Add all of the basic blocks and instructions
863 for (Function::const_iterator BB = FI->begin(),
864 E = FI->end(); BB != E; ++BB) {
865 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
867 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
868 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
877 void CppWriter::printVariableUses(const GlobalVariable *GV) {
878 nl(Out) << "// Type Definitions";
880 printType(GV->getType());
881 if (GV->hasInitializer()) {
882 Constant* Init = GV->getInitializer();
883 printType(Init->getType());
884 if (Function* F = dyn_cast<Function>(Init)) {
885 nl(Out)<< "/ Function Declarations"; nl(Out);
886 printFunctionHead(F);
887 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
888 nl(Out) << "// Global Variable Declarations"; nl(Out);
889 printVariableHead(gv);
891 nl(Out) << "// Constant Definitions"; nl(Out);
894 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
895 nl(Out) << "// Global Variable Definitions"; nl(Out);
896 printVariableBody(gv);
901 void CppWriter::printVariableHead(const GlobalVariable *GV) {
902 nl(Out) << "GlobalVariable* " << getCppName(GV);
904 Out << " = mod->getGlobalVariable(";
905 printEscapedString(GV->getName());
906 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
907 nl(Out) << "if (!" << getCppName(GV) << ") {";
908 in(); nl(Out) << getCppName(GV);
910 Out << " = new GlobalVariable(";
911 nl(Out) << "/*Type=*/";
912 printCppName(GV->getType()->getElementType());
914 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
916 nl(Out) << "/*Linkage=*/";
917 printLinkageType(GV->getLinkage());
919 nl(Out) << "/*Initializer=*/0, ";
920 if (GV->hasInitializer()) {
921 Out << "// has initializer, specified below";
923 nl(Out) << "/*Name=*/\"";
924 printEscapedString(GV->getName());
929 if (GV->hasSection()) {
931 Out << "->setSection(\"";
932 printEscapedString(GV->getSection());
936 if (GV->getAlignment()) {
938 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
942 out(); Out << "}"; nl(Out);
947 CppWriter::printVariableBody(const GlobalVariable *GV) {
948 if (GV->hasInitializer()) {
950 Out << "->setInitializer(";
951 //if (!isa<GlobalValue(GV->getInitializer()))
953 Out << getCppName(GV->getInitializer()) << ");";
959 CppWriter::getOpName(Value* V) {
960 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
961 return getCppName(V);
963 // See if its alread in the map of forward references, if so just return the
964 // name we already set up for it
965 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
966 if (I != ForwardRefs.end())
969 // This is a new forward reference. Generate a unique name for it
970 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
972 // Yes, this is a hack. An Argument is the smallest instantiable value that
973 // we can make as a placeholder for the real value. We'll replace these
974 // Argument instances later.
975 Out << "Argument* " << result << " = new Argument("
976 << getCppName(V->getType()) << ");";
978 ForwardRefs[V] = result;
982 // printInstruction - This member is called for each Instruction in a function.
984 CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
985 std::string iName(getCppName(I));
987 // Before we emit this instruction, we need to take care of generating any
988 // forward references. So, we get the names of all the operands in advance
989 std::string* opNames = new std::string[I->getNumOperands()];
990 for (unsigned i = 0; i < I->getNumOperands(); i++) {
991 opNames[i] = getOpName(I->getOperand(i));
994 switch (I->getOpcode()) {
995 case Instruction::Ret: {
996 const ReturnInst* ret = cast<ReturnInst>(I);
997 Out << "ReturnInst* " << iName << " = new ReturnInst("
998 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1001 case Instruction::Br: {
1002 const BranchInst* br = cast<BranchInst>(I);
1003 Out << "BranchInst* " << iName << " = new BranchInst(" ;
1004 if (br->getNumOperands() == 3 ) {
1005 Out << opNames[0] << ", "
1006 << opNames[1] << ", "
1007 << opNames[2] << ", ";
1009 } else if (br->getNumOperands() == 1) {
1010 Out << opNames[0] << ", ";
1012 error("Branch with 2 operands?");
1014 Out << bbname << ");";
1017 case Instruction::Switch: {
1018 const SwitchInst* sw = cast<SwitchInst>(I);
1019 Out << "SwitchInst* " << iName << " = new SwitchInst("
1020 << opNames[0] << ", "
1021 << opNames[1] << ", "
1022 << sw->getNumCases() << ", " << bbname << ");";
1024 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1025 Out << iName << "->addCase("
1026 << opNames[i] << ", "
1027 << opNames[i+1] << ");";
1032 case Instruction::Invoke: {
1033 const InvokeInst* inv = cast<InvokeInst>(I);
1034 Out << "std::vector<Value*> " << iName << "_params;";
1036 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1037 Out << iName << "_params.push_back("
1038 << opNames[i] << ");";
1041 Out << "InvokeInst* " << iName << " = new InvokeInst("
1042 << opNames[0] << ", "
1043 << opNames[1] << ", "
1044 << opNames[2] << ", "
1045 << iName << "_params, \"";
1046 printEscapedString(inv->getName());
1047 Out << "\", " << bbname << ");";
1048 nl(Out) << iName << "->setCallingConv(";
1049 printCallingConv(inv->getCallingConv());
1053 case Instruction::Unwind: {
1054 Out << "UnwindInst* " << iName << " = new UnwindInst("
1058 case Instruction::Unreachable:{
1059 Out << "UnreachableInst* " << iName << " = new UnreachableInst("
1063 case Instruction::Add:
1064 case Instruction::Sub:
1065 case Instruction::Mul:
1066 case Instruction::UDiv:
1067 case Instruction::SDiv:
1068 case Instruction::FDiv:
1069 case Instruction::URem:
1070 case Instruction::SRem:
1071 case Instruction::FRem:
1072 case Instruction::And:
1073 case Instruction::Or:
1074 case Instruction::Xor:
1075 case Instruction::Shl:
1076 case Instruction::LShr:
1077 case Instruction::AShr:{
1078 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1079 switch (I->getOpcode()) {
1080 case Instruction::Add: Out << "Instruction::Add"; break;
1081 case Instruction::Sub: Out << "Instruction::Sub"; break;
1082 case Instruction::Mul: Out << "Instruction::Mul"; break;
1083 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1084 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1085 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1086 case Instruction::URem:Out << "Instruction::URem"; break;
1087 case Instruction::SRem:Out << "Instruction::SRem"; break;
1088 case Instruction::FRem:Out << "Instruction::FRem"; break;
1089 case Instruction::And: Out << "Instruction::And"; break;
1090 case Instruction::Or: Out << "Instruction::Or"; break;
1091 case Instruction::Xor: Out << "Instruction::Xor"; break;
1092 case Instruction::Shl: Out << "Instruction::Shl"; break;
1093 case Instruction::LShr:Out << "Instruction::LShr"; break;
1094 case Instruction::AShr:Out << "Instruction::AShr"; break;
1095 default: Out << "Instruction::BadOpCode"; break;
1097 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1098 printEscapedString(I->getName());
1099 Out << "\", " << bbname << ");";
1102 case Instruction::FCmp: {
1103 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1104 switch (cast<FCmpInst>(I)->getPredicate()) {
1105 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1106 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1107 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1108 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1109 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1110 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1111 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1112 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1113 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1114 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1115 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1116 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1117 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1118 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1119 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1120 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1121 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1123 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1124 printEscapedString(I->getName());
1125 Out << "\", " << bbname << ");";
1128 case Instruction::ICmp: {
1129 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1130 switch (cast<ICmpInst>(I)->getPredicate()) {
1131 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1132 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1133 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1134 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1135 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1136 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1137 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1138 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1139 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1140 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1141 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1143 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1144 printEscapedString(I->getName());
1145 Out << "\", " << bbname << ");";
1148 case Instruction::Malloc: {
1149 const MallocInst* mallocI = cast<MallocInst>(I);
1150 Out << "MallocInst* " << iName << " = new MallocInst("
1151 << getCppName(mallocI->getAllocatedType()) << ", ";
1152 if (mallocI->isArrayAllocation())
1153 Out << opNames[0] << ", " ;
1155 printEscapedString(mallocI->getName());
1156 Out << "\", " << bbname << ");";
1157 if (mallocI->getAlignment())
1158 nl(Out) << iName << "->setAlignment("
1159 << mallocI->getAlignment() << ");";
1162 case Instruction::Free: {
1163 Out << "FreeInst* " << iName << " = new FreeInst("
1164 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1167 case Instruction::Alloca: {
1168 const AllocaInst* allocaI = cast<AllocaInst>(I);
1169 Out << "AllocaInst* " << iName << " = new AllocaInst("
1170 << getCppName(allocaI->getAllocatedType()) << ", ";
1171 if (allocaI->isArrayAllocation())
1172 Out << opNames[0] << ", ";
1174 printEscapedString(allocaI->getName());
1175 Out << "\", " << bbname << ");";
1176 if (allocaI->getAlignment())
1177 nl(Out) << iName << "->setAlignment("
1178 << allocaI->getAlignment() << ");";
1181 case Instruction::Load:{
1182 const LoadInst* load = cast<LoadInst>(I);
1183 Out << "LoadInst* " << iName << " = new LoadInst("
1184 << opNames[0] << ", \"";
1185 printEscapedString(load->getName());
1186 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1187 << ", " << bbname << ");";
1190 case Instruction::Store: {
1191 const StoreInst* store = cast<StoreInst>(I);
1192 Out << "StoreInst* " << iName << " = new StoreInst("
1193 << opNames[0] << ", "
1194 << opNames[1] << ", "
1195 << (store->isVolatile() ? "true" : "false")
1196 << ", " << bbname << ");";
1199 case Instruction::GetElementPtr: {
1200 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1201 if (gep->getNumOperands() <= 2) {
1202 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1204 if (gep->getNumOperands() == 2)
1205 Out << ", " << opNames[1];
1207 Out << "std::vector<Value*> " << iName << "_indices;";
1209 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1210 Out << iName << "_indices.push_back("
1211 << opNames[i] << ");";
1214 Out << "Instruction* " << iName << " = new GetElementPtrInst("
1215 << opNames[0] << ", " << iName << "_indices";
1218 printEscapedString(gep->getName());
1219 Out << "\", " << bbname << ");";
1222 case Instruction::PHI: {
1223 const PHINode* phi = cast<PHINode>(I);
1225 Out << "PHINode* " << iName << " = new PHINode("
1226 << getCppName(phi->getType()) << ", \"";
1227 printEscapedString(phi->getName());
1228 Out << "\", " << bbname << ");";
1229 nl(Out) << iName << "->reserveOperandSpace("
1230 << phi->getNumIncomingValues()
1233 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1234 Out << iName << "->addIncoming("
1235 << opNames[i] << ", " << opNames[i+1] << ");";
1240 case Instruction::Trunc:
1241 case Instruction::ZExt:
1242 case Instruction::SExt:
1243 case Instruction::FPTrunc:
1244 case Instruction::FPExt:
1245 case Instruction::FPToUI:
1246 case Instruction::FPToSI:
1247 case Instruction::UIToFP:
1248 case Instruction::SIToFP:
1249 case Instruction::PtrToInt:
1250 case Instruction::IntToPtr:
1251 case Instruction::BitCast: {
1252 const CastInst* cst = cast<CastInst>(I);
1253 Out << "CastInst* " << iName << " = new ";
1254 switch (I->getOpcode()) {
1255 case Instruction::Trunc: Out << "TruncInst";
1256 case Instruction::ZExt: Out << "ZExtInst";
1257 case Instruction::SExt: Out << "SExtInst";
1258 case Instruction::FPTrunc: Out << "FPTruncInst";
1259 case Instruction::FPExt: Out << "FPExtInst";
1260 case Instruction::FPToUI: Out << "FPToUIInst";
1261 case Instruction::FPToSI: Out << "FPToSIInst";
1262 case Instruction::UIToFP: Out << "UIToFPInst";
1263 case Instruction::SIToFP: Out << "SIToFPInst";
1264 case Instruction::PtrToInt: Out << "PtrToInst";
1265 case Instruction::IntToPtr: Out << "IntToPtrInst";
1266 case Instruction::BitCast: Out << "BitCastInst";
1267 default: assert(!"Unreachable"); break;
1269 Out << "(" << opNames[0] << ", "
1270 << getCppName(cst->getType()) << ", \"";
1271 printEscapedString(cst->getName());
1272 Out << "\", " << bbname << ");";
1275 case Instruction::Call:{
1276 const CallInst* call = cast<CallInst>(I);
1277 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1278 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1279 << getCppName(ila->getFunctionType()) << ", \""
1280 << ila->getAsmString() << "\", \""
1281 << ila->getConstraintString() << "\","
1282 << (ila->hasSideEffects() ? "true" : "false") << ");";
1285 if (call->getNumOperands() > 3) {
1286 Out << "std::vector<Value*> " << iName << "_params;";
1288 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1289 Out << iName << "_params.push_back(" << opNames[i] << ");";
1292 Out << "CallInst* " << iName << " = new CallInst("
1293 << opNames[0] << ", " << iName << "_params, \"";
1294 } else if (call->getNumOperands() == 3) {
1295 Out << "CallInst* " << iName << " = new CallInst("
1296 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1297 } else if (call->getNumOperands() == 2) {
1298 Out << "CallInst* " << iName << " = new CallInst("
1299 << opNames[0] << ", " << opNames[1] << ", \"";
1301 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
1304 printEscapedString(call->getName());
1305 Out << "\", " << bbname << ");";
1306 nl(Out) << iName << "->setCallingConv(";
1307 printCallingConv(call->getCallingConv());
1309 nl(Out) << iName << "->setTailCall("
1310 << (call->isTailCall() ? "true":"false");
1314 case Instruction::Select: {
1315 const SelectInst* sel = cast<SelectInst>(I);
1316 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
1317 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1318 printEscapedString(sel->getName());
1319 Out << "\", " << bbname << ");";
1322 case Instruction::UserOp1:
1324 case Instruction::UserOp2: {
1325 /// FIXME: What should be done here?
1328 case Instruction::VAArg: {
1329 const VAArgInst* va = cast<VAArgInst>(I);
1330 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1331 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1332 printEscapedString(va->getName());
1333 Out << "\", " << bbname << ");";
1336 case Instruction::ExtractElement: {
1337 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1338 Out << "ExtractElementInst* " << getCppName(eei)
1339 << " = new ExtractElementInst(" << opNames[0]
1340 << ", " << opNames[1] << ", \"";
1341 printEscapedString(eei->getName());
1342 Out << "\", " << bbname << ");";
1345 case Instruction::InsertElement: {
1346 const InsertElementInst* iei = cast<InsertElementInst>(I);
1347 Out << "InsertElementInst* " << getCppName(iei)
1348 << " = new InsertElementInst(" << opNames[0]
1349 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1350 printEscapedString(iei->getName());
1351 Out << "\", " << bbname << ");";
1354 case Instruction::ShuffleVector: {
1355 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1356 Out << "ShuffleVectorInst* " << getCppName(svi)
1357 << " = new ShuffleVectorInst(" << opNames[0]
1358 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1359 printEscapedString(svi->getName());
1360 Out << "\", " << bbname << ");";
1364 DefinedValues.insert(I);
1369 // Print out the types, constants and declarations needed by one function
1370 void CppWriter::printFunctionUses(const Function* F) {
1372 nl(Out) << "// Type Definitions"; nl(Out);
1374 // Print the function's return type
1375 printType(F->getReturnType());
1377 // Print the function's function type
1378 printType(F->getFunctionType());
1380 // Print the types of each of the function's arguments
1381 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1383 printType(AI->getType());
1387 // Print type definitions for every type referenced by an instruction and
1388 // make a note of any global values or constants that are referenced
1389 std::vector<GlobalValue*> gvs;
1390 std::vector<Constant*> consts;
1391 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1392 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1394 // Print the type of the instruction itself
1395 printType(I->getType());
1397 // Print the type of each of the instruction's operands
1398 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1399 Value* operand = I->getOperand(i);
1400 printType(operand->getType());
1401 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand))
1403 else if (Constant* C = dyn_cast<Constant>(operand))
1404 consts.push_back(C);
1409 // Print the function declarations for any functions encountered
1410 nl(Out) << "// Function Declarations"; nl(Out);
1411 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1413 if (Function* Fun = dyn_cast<Function>(*I)) {
1414 if (!is_inline || Fun != F)
1415 printFunctionHead(Fun);
1419 // Print the global variable declarations for any variables encountered
1420 nl(Out) << "// Global Variable Declarations"; nl(Out);
1421 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1423 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1424 printVariableHead(F);
1427 // Print the constants found
1428 nl(Out) << "// Constant Definitions"; nl(Out);
1429 for (std::vector<Constant*>::iterator I = consts.begin(), E = consts.end();
1434 // Process the global variables definitions now that all the constants have
1435 // been emitted. These definitions just couple the gvars with their constant
1437 nl(Out) << "// Global Variable Definitions"; nl(Out);
1438 for (std::vector<GlobalValue*>::iterator I = gvs.begin(), E = gvs.end();
1440 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1441 printVariableBody(GV);
1445 void CppWriter::printFunctionHead(const Function* F) {
1446 nl(Out) << "Function* " << getCppName(F);
1448 Out << " = mod->getFunction(\"";
1449 printEscapedString(F->getName());
1450 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1451 nl(Out) << "if (!" << getCppName(F) << ") {";
1452 nl(Out) << getCppName(F);
1454 Out<< " = new Function(";
1455 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1456 nl(Out) << "/*Linkage=*/";
1457 printLinkageType(F->getLinkage());
1459 nl(Out) << "/*Name=*/\"";
1460 printEscapedString(F->getName());
1461 Out << "\", mod); " << (F->isExternal()? "// (external, no body)" : "");
1464 Out << "->setCallingConv(";
1465 printCallingConv(F->getCallingConv());
1468 if (F->hasSection()) {
1470 Out << "->setSection(\"" << F->getSection() << "\");";
1473 if (F->getAlignment()) {
1475 Out << "->setAlignment(" << F->getAlignment() << ");";
1484 void CppWriter::printFunctionBody(const Function *F) {
1485 if (F->isExternal())
1486 return; // external functions have no bodies.
1488 // Clear the DefinedValues and ForwardRefs maps because we can't have
1489 // cross-function forward refs
1490 ForwardRefs.clear();
1491 DefinedValues.clear();
1493 // Create all the argument values
1495 if (!F->arg_empty()) {
1496 Out << "Function::arg_iterator args = " << getCppName(F)
1497 << "->arg_begin();";
1500 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1502 Out << "Value* " << getCppName(AI) << " = args++;";
1504 if (AI->hasName()) {
1505 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1511 // Create all the basic blocks
1513 for (Function::const_iterator BI = F->begin(), BE = F->end();
1515 std::string bbname(getCppName(BI));
1516 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
1518 printEscapedString(BI->getName());
1519 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1523 // Output all of its basic blocks... for the function
1524 for (Function::const_iterator BI = F->begin(), BE = F->end();
1526 std::string bbname(getCppName(BI));
1527 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1530 // Output all of the instructions in the basic block...
1531 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1533 printInstruction(I,bbname);
1537 // Loop over the ForwardRefs and resolve them now that all instructions
1539 if (!ForwardRefs.empty()) {
1540 nl(Out) << "// Resolve Forward References";
1544 while (!ForwardRefs.empty()) {
1545 ForwardRefMap::iterator I = ForwardRefs.begin();
1546 Out << I->second << "->replaceAllUsesWith("
1547 << getCppName(I->first) << "); delete " << I->second << ";";
1549 ForwardRefs.erase(I);
1553 void CppWriter::printInline(const std::string& fname, const std::string& func) {
1554 const Function* F = TheModule->getNamedFunction(func);
1556 error(std::string("Function '") + func + "' not found in input module");
1559 if (F->isExternal()) {
1560 error(std::string("Function '") + func + "' is external!");
1563 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1565 unsigned arg_count = 1;
1566 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1568 Out << ", Value* arg_" << arg_count;
1573 printFunctionUses(F);
1574 printFunctionBody(F);
1576 Out << "return " << getCppName(F->begin()) << ";";
1581 void CppWriter::printModuleBody() {
1582 // Print out all the type definitions
1583 nl(Out) << "// Type Definitions"; nl(Out);
1584 printTypes(TheModule);
1586 // Functions can call each other and global variables can reference them so
1587 // define all the functions first before emitting their function bodies.
1588 nl(Out) << "// Function Declarations"; nl(Out);
1589 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1591 printFunctionHead(I);
1593 // Process the global variables declarations. We can't initialze them until
1594 // after the constants are printed so just print a header for each global
1595 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1596 for (Module::const_global_iterator I = TheModule->global_begin(),
1597 E = TheModule->global_end(); I != E; ++I) {
1598 printVariableHead(I);
1601 // Print out all the constants definitions. Constants don't recurse except
1602 // through GlobalValues. All GlobalValues have been declared at this point
1603 // so we can proceed to generate the constants.
1604 nl(Out) << "// Constant Definitions"; nl(Out);
1605 printConstants(TheModule);
1607 // Process the global variables definitions now that all the constants have
1608 // been emitted. These definitions just couple the gvars with their constant
1610 nl(Out) << "// Global Variable Definitions"; nl(Out);
1611 for (Module::const_global_iterator I = TheModule->global_begin(),
1612 E = TheModule->global_end(); I != E; ++I) {
1613 printVariableBody(I);
1616 // Finally, we can safely put out all of the function bodies.
1617 nl(Out) << "// Function Definitions"; nl(Out);
1618 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1620 if (!I->isExternal()) {
1621 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1625 printFunctionBody(I);
1632 void CppWriter::printProgram(
1633 const std::string& fname,
1634 const std::string& mName
1636 Out << "#include <llvm/Module.h>\n";
1637 Out << "#include <llvm/DerivedTypes.h>\n";
1638 Out << "#include <llvm/Constants.h>\n";
1639 Out << "#include <llvm/GlobalVariable.h>\n";
1640 Out << "#include <llvm/Function.h>\n";
1641 Out << "#include <llvm/CallingConv.h>\n";
1642 Out << "#include <llvm/BasicBlock.h>\n";
1643 Out << "#include <llvm/Instructions.h>\n";
1644 Out << "#include <llvm/InlineAsm.h>\n";
1645 Out << "#include <llvm/Support/MathExtras.h>\n";
1646 Out << "#include <llvm/Pass.h>\n";
1647 Out << "#include <llvm/PassManager.h>\n";
1648 Out << "#include <llvm/Analysis/Verifier.h>\n";
1649 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1650 Out << "#include <algorithm>\n";
1651 Out << "#include <iostream>\n\n";
1652 Out << "using namespace llvm;\n\n";
1653 Out << "Module* " << fname << "();\n\n";
1654 Out << "int main(int argc, char**argv) {\n";
1655 Out << " Module* Mod = makeLLVMModule();\n";
1656 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1657 Out << " std::cerr.flush();\n";
1658 Out << " std::cout.flush();\n";
1659 Out << " PassManager PM;\n";
1660 Out << " PM.add(new PrintModulePass(&std::cout));\n";
1661 Out << " PM.run(*Mod);\n";
1662 Out << " return 0;\n";
1664 printModule(fname,mName);
1667 void CppWriter::printModule(
1668 const std::string& fname,
1669 const std::string& mName
1671 nl(Out) << "Module* " << fname << "() {";
1672 nl(Out,1) << "// Module Construction";
1673 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1674 nl(Out) << "mod->setEndianness(";
1675 switch (TheModule->getEndianness()) {
1676 case Module::LittleEndian: Out << "Module::LittleEndian);"; break;
1677 case Module::BigEndian: Out << "Module::BigEndian);"; break;
1678 case Module::AnyEndianness:Out << "Module::AnyEndianness);"; break;
1680 nl(Out) << "mod->setPointerSize(";
1681 switch (TheModule->getPointerSize()) {
1682 case Module::Pointer32: Out << "Module::Pointer32);"; break;
1683 case Module::Pointer64: Out << "Module::Pointer64);"; break;
1684 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);"; break;
1687 if (!TheModule->getTargetTriple().empty()) {
1688 Out << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1693 if (!TheModule->getModuleInlineAsm().empty()) {
1694 Out << "mod->setModuleInlineAsm(\"";
1695 printEscapedString(TheModule->getModuleInlineAsm());
1700 // Loop over the dependent libraries and emit them.
1701 Module::lib_iterator LI = TheModule->lib_begin();
1702 Module::lib_iterator LE = TheModule->lib_end();
1704 Out << "mod->addLibrary(\"" << *LI << "\");";
1709 nl(Out) << "return mod;";
1714 void CppWriter::printContents(
1715 const std::string& fname, // Name of generated function
1716 const std::string& mName // Name of module generated module
1718 Out << "\nModule* " << fname << "(Module *mod) {\n";
1719 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1721 Out << "\nreturn mod;\n";
1725 void CppWriter::printFunction(
1726 const std::string& fname, // Name of generated function
1727 const std::string& funcName // Name of function to generate
1729 const Function* F = TheModule->getNamedFunction(funcName);
1731 error(std::string("Function '") + funcName + "' not found in input module");
1734 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1735 printFunctionUses(F);
1736 printFunctionHead(F);
1737 printFunctionBody(F);
1738 Out << "return " << getCppName(F) << ";\n";
1742 void CppWriter::printVariable(
1743 const std::string& fname, /// Name of generated function
1744 const std::string& varName // Name of variable to generate
1746 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1749 error(std::string("Variable '") + varName + "' not found in input module");
1752 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1753 printVariableUses(GV);
1754 printVariableHead(GV);
1755 printVariableBody(GV);
1756 Out << "return " << getCppName(GV) << ";\n";
1760 void CppWriter::printType(
1761 const std::string& fname, /// Name of generated function
1762 const std::string& typeName // Name of type to generate
1764 const Type* Ty = TheModule->getTypeByName(typeName);
1766 error(std::string("Type '") + typeName + "' not found in input module");
1769 Out << "\nType* " << fname << "(Module *mod) {\n";
1771 Out << "return " << getCppName(Ty) << ";\n";
1775 } // end anonymous llvm
1779 void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1780 // Initialize a CppWriter for us to use
1781 CppWriter W(o, mod);
1784 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1786 // Get the name of the function we're supposed to generate
1787 std::string fname = FuncName.getValue();
1789 // Get the name of the thing we are to generate
1790 std::string tgtname = NameToGenerate.getValue();
1791 if (GenerationType == GenModule ||
1792 GenerationType == GenContents ||
1793 GenerationType == GenProgram) {
1794 if (tgtname == "!bad!") {
1795 if (mod->getModuleIdentifier() == "-")
1796 tgtname = "<stdin>";
1798 tgtname = mod->getModuleIdentifier();
1800 } else if (tgtname == "!bad!") {
1801 W.error("You must use the -for option with -gen-{function,variable,type}");
1804 switch (WhatToGenerate(GenerationType)) {
1807 fname = "makeLLVMModule";
1808 W.printProgram(fname,tgtname);
1812 fname = "makeLLVMModule";
1813 W.printModule(fname,tgtname);
1817 fname = "makeLLVMModuleContents";
1818 W.printContents(fname,tgtname);
1822 fname = "makeLLVMFunction";
1823 W.printFunction(fname,tgtname);
1827 fname = "makeLLVMInline";
1828 W.printInline(fname,tgtname);
1832 fname = "makeLLVMVariable";
1833 W.printVariable(fname,tgtname);
1837 fname = "makeLLVMType";
1838 W.printType(fname,tgtname);
1841 W.error("Invalid generation option");