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/ADT/SmallPtrSet.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Config/config.h"
38 static cl::opt<std::string>
39 FuncName("funcname", cl::desc("Specify the name of the generated function"),
40 cl::value_desc("function name"));
52 static cl::opt<WhatToGenerate> GenerationType(cl::Optional,
53 cl::desc("Choose what kind of output to generate"),
56 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
57 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
58 clEnumValN(GenContents,"gen-contents", "Generate contents of a module"),
59 clEnumValN(GenFunction,"gen-function", "Generate a function definition"),
60 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
61 clEnumValN(GenVariable,"gen-variable", "Generate a variable definition"),
62 clEnumValN(GenType, "gen-type", "Generate a type definition"),
67 static cl::opt<std::string> NameToGenerate("for", cl::Optional,
68 cl::desc("Specify the name of the thing to generate"),
72 typedef std::vector<const Type*> TypeList;
73 typedef std::map<const Type*,std::string> TypeMap;
74 typedef std::map<const Value*,std::string> ValueMap;
75 typedef std::set<std::string> NameSet;
76 typedef std::set<const Type*> TypeSet;
77 typedef std::set<const Value*> ValueSet;
78 typedef std::map<const Value*,std::string> ForwardRefMap;
83 const Module *TheModule;
87 TypeMap UnresolvedTypes;
91 ValueSet DefinedValues;
92 ForwardRefMap ForwardRefs;
96 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
97 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
98 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
100 const Module* getModule() { return TheModule; }
102 void printProgram(const std::string& fname, const std::string& modName );
103 void printModule(const std::string& fname, const std::string& modName );
104 void printContents(const std::string& fname, const std::string& modName );
105 void printFunction(const std::string& fname, const std::string& funcName );
106 void printInline(const std::string& fname, const std::string& funcName );
107 void printVariable(const std::string& fname, const std::string& varName );
108 void printType(const std::string& fname, const std::string& typeName );
110 void error(const std::string& msg);
113 void printLinkageType(GlobalValue::LinkageTypes LT);
114 void printCallingConv(unsigned cc);
115 void printEscapedString(const std::string& str);
116 void printCFP(const ConstantFP* CFP);
118 std::string getCppName(const Type* val);
119 inline void printCppName(const Type* val);
121 std::string getCppName(const Value* val);
122 inline void printCppName(const Value* val);
124 bool printTypeInternal(const Type* Ty);
125 inline void printType(const Type* Ty);
126 void printTypes(const Module* M);
128 void printConstant(const Constant *CPV);
129 void printConstants(const Module* M);
131 void printVariableUses(const GlobalVariable *GV);
132 void printVariableHead(const GlobalVariable *GV);
133 void printVariableBody(const GlobalVariable *GV);
135 void printFunctionUses(const Function *F);
136 void printFunctionHead(const Function *F);
137 void printFunctionBody(const Function *F);
138 void printInstruction(const Instruction *I, const std::string& bbname);
139 std::string getOpName(Value*);
141 void printModuleBody();
145 static unsigned indent_level = 0;
146 inline std::ostream& nl(std::ostream& Out, int delta = 0) {
148 if (delta >= 0 || indent_level >= unsigned(-delta))
149 indent_level += delta;
150 for (unsigned i = 0; i < indent_level; ++i)
155 inline void in() { indent_level++; }
156 inline void out() { if (indent_level >0) indent_level--; }
159 sanitize(std::string& str) {
160 for (size_t i = 0; i < str.length(); ++i)
161 if (!isalnum(str[i]) && str[i] != '_')
166 getTypePrefix(const Type* Ty ) {
167 switch (Ty->getTypeID()) {
168 case Type::VoidTyID: return "void_";
169 case Type::IntegerTyID:
170 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
172 case Type::FloatTyID: return "float_";
173 case Type::DoubleTyID: return "double_";
174 case Type::LabelTyID: return "label_";
175 case Type::FunctionTyID: return "func_";
176 case Type::StructTyID: return "struct_";
177 case Type::ArrayTyID: return "array_";
178 case Type::PointerTyID: return "ptr_";
179 case Type::VectorTyID: return "packed_";
180 case Type::OpaqueTyID: return "opaque_";
181 default: return "other_";
186 // Looks up the type in the symbol table and returns a pointer to its name or
187 // a null pointer if it wasn't found. Note that this isn't the same as the
188 // Mode::getTypeName function which will return an empty string, not a null
189 // pointer if the name is not found.
190 inline const std::string*
191 findTypeName(const TypeSymbolTable& ST, const Type* Ty)
193 TypeSymbolTable::const_iterator TI = ST.begin();
194 TypeSymbolTable::const_iterator TE = ST.end();
195 for (;TI != TE; ++TI)
196 if (TI->second == Ty)
202 CppWriter::error(const std::string& msg) {
203 std::cerr << progname << ": " << msg << "\n";
207 // printCFP - Print a floating point constant .. very carefully :)
208 // This makes sure that conversion to/from floating yields the same binary
209 // result so that we don't lose precision.
211 CppWriter::printCFP(const ConstantFP *CFP) {
212 APFloat APF = APFloat(CFP->getValueAPF()); // copy
213 if (CFP->getType() == Type::FloatTy)
214 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
215 Out << "ConstantFP::get(";
216 if (CFP->getType() == Type::DoubleTy)
217 Out << "Type::DoubleTy, ";
219 Out << "Type::FloatTy, ";
223 sprintf(Buffer, "%A", APF.convertToDouble());
224 if ((!strncmp(Buffer, "0x", 2) ||
225 !strncmp(Buffer, "-0x", 3) ||
226 !strncmp(Buffer, "+0x", 3)) &&
227 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
228 if (CFP->getType() == Type::DoubleTy)
229 Out << "BitsToDouble(" << Buffer << ")";
231 Out << "BitsToFloat((float)" << Buffer << ")";
235 std::string StrVal = ftostr(CFP->getValueAPF());
237 while (StrVal[0] == ' ')
238 StrVal.erase(StrVal.begin());
240 // Check to make sure that the stringized number is not some string like
241 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
242 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
243 ((StrVal[0] == '-' || StrVal[0] == '+') &&
244 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
245 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
246 if (CFP->getType() == Type::DoubleTy)
249 Out << StrVal << "f";
251 else if (CFP->getType() == Type::DoubleTy)
252 Out << "BitsToDouble(0x" << std::hex
253 << CFP->getValueAPF().convertToAPInt().getZExtValue()
254 << std::dec << "ULL) /* " << StrVal << " */";
256 Out << "BitsToFloat(0x" << std::hex
257 << (uint32_t)CFP->getValueAPF().convertToAPInt().getZExtValue()
258 << std::dec << "U) /* " << StrVal << " */";
267 CppWriter::printCallingConv(unsigned cc){
268 // Print the calling convention.
270 case CallingConv::C: Out << "CallingConv::C"; break;
271 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
272 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
273 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
274 default: Out << cc; break;
279 CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
281 case GlobalValue::InternalLinkage:
282 Out << "GlobalValue::InternalLinkage"; break;
283 case GlobalValue::LinkOnceLinkage:
284 Out << "GlobalValue::LinkOnceLinkage "; break;
285 case GlobalValue::WeakLinkage:
286 Out << "GlobalValue::WeakLinkage"; break;
287 case GlobalValue::AppendingLinkage:
288 Out << "GlobalValue::AppendingLinkage"; break;
289 case GlobalValue::ExternalLinkage:
290 Out << "GlobalValue::ExternalLinkage"; break;
291 case GlobalValue::DLLImportLinkage:
292 Out << "GlobalValue::DLLImportLinkage"; break;
293 case GlobalValue::DLLExportLinkage:
294 Out << "GlobalValue::DLLExportLinkage"; break;
295 case GlobalValue::ExternalWeakLinkage:
296 Out << "GlobalValue::ExternalWeakLinkage"; break;
297 case GlobalValue::GhostLinkage:
298 Out << "GlobalValue::GhostLinkage"; break;
302 // printEscapedString - Print each character of the specified string, escaping
303 // it if it is not printable or if it is an escape char.
305 CppWriter::printEscapedString(const std::string &Str) {
306 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
307 unsigned char C = Str[i];
308 if (isprint(C) && C != '"' && C != '\\') {
312 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
313 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
319 CppWriter::getCppName(const Type* Ty)
321 // First, handle the primitive types .. easy
322 if (Ty->isPrimitiveType() || Ty->isInteger()) {
323 switch (Ty->getTypeID()) {
324 case Type::VoidTyID: return "Type::VoidTy";
325 case Type::IntegerTyID: {
326 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
327 return "IntegerType::get(" + utostr(BitWidth) + ")";
329 case Type::FloatTyID: return "Type::FloatTy";
330 case Type::DoubleTyID: return "Type::DoubleTy";
331 case Type::LabelTyID: return "Type::LabelTy";
333 error("Invalid primitive type");
336 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
339 // Now, see if we've seen the type before and return that
340 TypeMap::iterator I = TypeNames.find(Ty);
341 if (I != TypeNames.end())
344 // Okay, let's build a new name for this type. Start with a prefix
345 const char* prefix = 0;
346 switch (Ty->getTypeID()) {
347 case Type::FunctionTyID: prefix = "FuncTy_"; break;
348 case Type::StructTyID: prefix = "StructTy_"; break;
349 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
350 case Type::PointerTyID: prefix = "PointerTy_"; break;
351 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
352 case Type::VectorTyID: prefix = "VectorTy_"; break;
353 default: prefix = "OtherTy_"; break; // prevent breakage
356 // See if the type has a name in the symboltable and build accordingly
357 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
360 name = std::string(prefix) + *tName;
362 name = std::string(prefix) + utostr(uniqueNum++);
366 return TypeNames[Ty] = name;
370 CppWriter::printCppName(const Type* Ty)
372 printEscapedString(getCppName(Ty));
376 CppWriter::getCppName(const Value* val) {
378 ValueMap::iterator I = ValueNames.find(val);
379 if (I != ValueNames.end() && I->first == val)
382 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
383 name = std::string("gvar_") +
384 getTypePrefix(GV->getType()->getElementType());
385 } else if (isa<Function>(val)) {
386 name = std::string("func_");
387 } else if (const Constant* C = dyn_cast<Constant>(val)) {
388 name = std::string("const_") + getTypePrefix(C->getType());
389 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
391 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
392 Function::const_arg_iterator(Arg)) + 1;
393 name = std::string("arg_") + utostr(argNum);
394 NameSet::iterator NI = UsedNames.find(name);
395 if (NI != UsedNames.end())
396 name += std::string("_") + utostr(uniqueNum++);
397 UsedNames.insert(name);
398 return ValueNames[val] = name;
400 name = getTypePrefix(val->getType());
403 name = getTypePrefix(val->getType());
405 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
407 NameSet::iterator NI = UsedNames.find(name);
408 if (NI != UsedNames.end())
409 name += std::string("_") + utostr(uniqueNum++);
410 UsedNames.insert(name);
411 return ValueNames[val] = name;
415 CppWriter::printCppName(const Value* val) {
416 printEscapedString(getCppName(val));
420 CppWriter::printTypeInternal(const Type* Ty) {
421 // We don't print definitions for primitive types
422 if (Ty->isPrimitiveType() || Ty->isInteger())
425 // If we already defined this type, we don't need to define it again.
426 if (DefinedTypes.find(Ty) != DefinedTypes.end())
429 // Everything below needs the name for the type so get it now.
430 std::string typeName(getCppName(Ty));
432 // Search the type stack for recursion. If we find it, then generate this
433 // as an OpaqueType, but make sure not to do this multiple times because
434 // the type could appear in multiple places on the stack. Once the opaque
435 // definition is issued, it must not be re-issued. Consequently we have to
436 // check the UnresolvedTypes list as well.
437 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
438 if (TI != TypeStack.end()) {
439 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
440 if (I == UnresolvedTypes.end()) {
441 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
443 UnresolvedTypes[Ty] = typeName;
448 // We're going to print a derived type which, by definition, contains other
449 // types. So, push this one we're printing onto the type stack to assist with
450 // recursive definitions.
451 TypeStack.push_back(Ty);
453 // Print the type definition
454 switch (Ty->getTypeID()) {
455 case Type::FunctionTyID: {
456 const FunctionType* FT = cast<FunctionType>(Ty);
457 Out << "std::vector<const Type*>" << typeName << "_args;";
459 FunctionType::param_iterator PI = FT->param_begin();
460 FunctionType::param_iterator PE = FT->param_end();
461 for (; PI != PE; ++PI) {
462 const Type* argTy = static_cast<const Type*>(*PI);
463 bool isForward = printTypeInternal(argTy);
464 std::string argName(getCppName(argTy));
465 Out << typeName << "_args.push_back(" << argName;
471 const ParamAttrsList *PAL = FT->getParamAttrs();
472 Out << "ParamAttrsList *" << typeName << "_PAL = 0;";
475 Out << '{'; in(); nl(Out);
476 Out << "ParamAttrsVector Attrs;"; nl(Out);
477 Out << "ParamAttrsWithIndex PAWI;"; nl(Out);
478 for (unsigned i = 0; i < PAL->size(); ++i) {
479 uint16_t index = PAL->getParamIndex(i);
480 uint16_t attrs = PAL->getParamAttrs(index);
481 Out << "PAWI.index = " << index << "; PAWI.attrs = 0 ";
482 if (attrs & ParamAttr::SExt)
483 Out << " | ParamAttr::SExt";
484 if (attrs & ParamAttr::ZExt)
485 Out << " | ParamAttr::ZExt";
486 if (attrs & ParamAttr::NoAlias)
487 Out << " | ParamAttr::NoAlias";
488 if (attrs & ParamAttr::StructRet)
489 Out << " | ParamAttr::StructRet";
490 if (attrs & ParamAttr::InReg)
491 Out << " | ParamAttr::InReg";
492 if (attrs & ParamAttr::NoReturn)
493 Out << " | ParamAttr::NoReturn";
494 if (attrs & ParamAttr::NoUnwind)
495 Out << " | ParamAttr::NoUnwind";
498 Out << "Attrs.push_back(PAWI);";
501 Out << typeName << "_PAL = ParamAttrsList::get(Attrs);";
506 bool isForward = printTypeInternal(FT->getReturnType());
507 std::string retTypeName(getCppName(FT->getReturnType()));
508 Out << "FunctionType* " << typeName << " = FunctionType::get(";
509 in(); nl(Out) << "/*Result=*/" << retTypeName;
513 nl(Out) << "/*Params=*/" << typeName << "_args,";
514 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true," : "false,") ;
515 nl(Out) << "/*ParamAttrs=*/" << typeName << "_PAL" << ");";
520 case Type::StructTyID: {
521 const StructType* ST = cast<StructType>(Ty);
522 Out << "std::vector<const Type*>" << typeName << "_fields;";
524 StructType::element_iterator EI = ST->element_begin();
525 StructType::element_iterator EE = ST->element_end();
526 for (; EI != EE; ++EI) {
527 const Type* fieldTy = static_cast<const Type*>(*EI);
528 bool isForward = printTypeInternal(fieldTy);
529 std::string fieldName(getCppName(fieldTy));
530 Out << typeName << "_fields.push_back(" << fieldName;
536 Out << "StructType* " << typeName << " = StructType::get("
537 << typeName << "_fields, /*isPacked=*/"
538 << (ST->isPacked() ? "true" : "false") << ");";
542 case Type::ArrayTyID: {
543 const ArrayType* AT = cast<ArrayType>(Ty);
544 const Type* ET = AT->getElementType();
545 bool isForward = printTypeInternal(ET);
546 std::string elemName(getCppName(ET));
547 Out << "ArrayType* " << typeName << " = ArrayType::get("
548 << elemName << (isForward ? "_fwd" : "")
549 << ", " << utostr(AT->getNumElements()) << ");";
553 case Type::PointerTyID: {
554 const PointerType* PT = cast<PointerType>(Ty);
555 const Type* ET = PT->getElementType();
556 bool isForward = printTypeInternal(ET);
557 std::string elemName(getCppName(ET));
558 Out << "PointerType* " << typeName << " = PointerType::get("
559 << elemName << (isForward ? "_fwd" : "") << ");";
563 case Type::VectorTyID: {
564 const VectorType* PT = cast<VectorType>(Ty);
565 const Type* ET = PT->getElementType();
566 bool isForward = printTypeInternal(ET);
567 std::string elemName(getCppName(ET));
568 Out << "VectorType* " << typeName << " = VectorType::get("
569 << elemName << (isForward ? "_fwd" : "")
570 << ", " << utostr(PT->getNumElements()) << ");";
574 case Type::OpaqueTyID: {
575 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
580 error("Invalid TypeID");
583 // If the type had a name, make sure we recreate it.
584 const std::string* progTypeName =
585 findTypeName(TheModule->getTypeSymbolTable(),Ty);
587 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
592 // Pop us off the type stack
593 TypeStack.pop_back();
595 // Indicate that this type is now defined.
596 DefinedTypes.insert(Ty);
598 // Early resolve as many unresolved types as possible. Search the unresolved
599 // types map for the type we just printed. Now that its definition is complete
600 // we can resolve any previous references to it. This prevents a cascade of
602 TypeMap::iterator I = UnresolvedTypes.find(Ty);
603 if (I != UnresolvedTypes.end()) {
604 Out << "cast<OpaqueType>(" << I->second
605 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
607 Out << I->second << " = cast<";
608 switch (Ty->getTypeID()) {
609 case Type::FunctionTyID: Out << "FunctionType"; break;
610 case Type::ArrayTyID: Out << "ArrayType"; break;
611 case Type::StructTyID: Out << "StructType"; break;
612 case Type::VectorTyID: Out << "VectorType"; break;
613 case Type::PointerTyID: Out << "PointerType"; break;
614 case Type::OpaqueTyID: Out << "OpaqueType"; break;
615 default: Out << "NoSuchDerivedType"; break;
617 Out << ">(" << I->second << "_fwd.get());";
619 UnresolvedTypes.erase(I);
622 // Finally, separate the type definition from other with a newline.
625 // We weren't a recursive type
629 // Prints a type definition. Returns true if it could not resolve all the types
630 // in the definition but had to use a forward reference.
632 CppWriter::printType(const Type* Ty) {
633 assert(TypeStack.empty());
635 printTypeInternal(Ty);
636 assert(TypeStack.empty());
640 CppWriter::printTypes(const Module* M) {
642 // Walk the symbol table and print out all its types
643 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
644 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
647 // For primitive types and types already defined, just add a name
648 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
649 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
650 TNI != TypeNames.end()) {
651 Out << "mod->addTypeName(\"";
652 printEscapedString(TI->first);
653 Out << "\", " << getCppName(TI->second) << ");";
655 // For everything else, define the type
657 printType(TI->second);
661 // Add all of the global variables to the value table...
662 for (Module::const_global_iterator I = TheModule->global_begin(),
663 E = TheModule->global_end(); I != E; ++I) {
664 if (I->hasInitializer())
665 printType(I->getInitializer()->getType());
666 printType(I->getType());
669 // Add all the functions to the table
670 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
672 printType(FI->getReturnType());
673 printType(FI->getFunctionType());
674 // Add all the function arguments
675 for(Function::const_arg_iterator AI = FI->arg_begin(),
676 AE = FI->arg_end(); AI != AE; ++AI) {
677 printType(AI->getType());
680 // Add all of the basic blocks and instructions
681 for (Function::const_iterator BB = FI->begin(),
682 E = FI->end(); BB != E; ++BB) {
683 printType(BB->getType());
684 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
686 printType(I->getType());
687 for (unsigned i = 0; i < I->getNumOperands(); ++i)
688 printType(I->getOperand(i)->getType());
695 // printConstant - Print out a constant pool entry...
696 void CppWriter::printConstant(const Constant *CV) {
697 // First, if the constant is actually a GlobalValue (variable or function) or
698 // its already in the constant list then we've printed it already and we can
700 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
703 std::string constName(getCppName(CV));
704 std::string typeName(getCppName(CV->getType()));
705 if (CV->isNullValue()) {
706 Out << "Constant* " << constName << " = Constant::getNullValue("
711 if (isa<GlobalValue>(CV)) {
712 // Skip variables and functions, we emit them elsewhere
715 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
716 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
717 << cast<IntegerType>(CI->getType())->getBitWidth() << ", "
718 << " \"" << CI->getValue().toStringSigned(10) << "\", 10));";
719 } else if (isa<ConstantAggregateZero>(CV)) {
720 Out << "ConstantAggregateZero* " << constName
721 << " = ConstantAggregateZero::get(" << typeName << ");";
722 } else if (isa<ConstantPointerNull>(CV)) {
723 Out << "ConstantPointerNull* " << constName
724 << " = ConstanPointerNull::get(" << typeName << ");";
725 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
726 Out << "ConstantFP* " << constName << " = ";
729 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
730 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
731 Out << "Constant* " << constName << " = ConstantArray::get(\"";
732 std::string tmp = CA->getAsString();
733 bool nullTerminate = false;
734 if (tmp[tmp.length()-1] == 0) {
735 tmp.erase(tmp.length()-1);
736 nullTerminate = true;
738 printEscapedString(tmp);
739 // Determine if we want null termination or not.
741 Out << "\", true"; // Indicate that the null terminator should be added.
743 Out << "\", false";// No null terminator
746 Out << "std::vector<Constant*> " << constName << "_elems;";
748 unsigned N = CA->getNumOperands();
749 for (unsigned i = 0; i < N; ++i) {
750 printConstant(CA->getOperand(i)); // recurse to print operands
751 Out << constName << "_elems.push_back("
752 << getCppName(CA->getOperand(i)) << ");";
755 Out << "Constant* " << constName << " = ConstantArray::get("
756 << typeName << ", " << constName << "_elems);";
758 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
759 Out << "std::vector<Constant*> " << constName << "_fields;";
761 unsigned N = CS->getNumOperands();
762 for (unsigned i = 0; i < N; i++) {
763 printConstant(CS->getOperand(i));
764 Out << constName << "_fields.push_back("
765 << getCppName(CS->getOperand(i)) << ");";
768 Out << "Constant* " << constName << " = ConstantStruct::get("
769 << typeName << ", " << constName << "_fields);";
770 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
771 Out << "std::vector<Constant*> " << constName << "_elems;";
773 unsigned N = CP->getNumOperands();
774 for (unsigned i = 0; i < N; ++i) {
775 printConstant(CP->getOperand(i));
776 Out << constName << "_elems.push_back("
777 << getCppName(CP->getOperand(i)) << ");";
780 Out << "Constant* " << constName << " = ConstantVector::get("
781 << typeName << ", " << constName << "_elems);";
782 } else if (isa<UndefValue>(CV)) {
783 Out << "UndefValue* " << constName << " = UndefValue::get("
785 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
786 if (CE->getOpcode() == Instruction::GetElementPtr) {
787 Out << "std::vector<Constant*> " << constName << "_indices;";
789 printConstant(CE->getOperand(0));
790 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
791 printConstant(CE->getOperand(i));
792 Out << constName << "_indices.push_back("
793 << getCppName(CE->getOperand(i)) << ");";
796 Out << "Constant* " << constName
797 << " = ConstantExpr::getGetElementPtr("
798 << getCppName(CE->getOperand(0)) << ", "
799 << "&" << constName << "_indices[0], "
800 << constName << "_indices.size()"
802 } else if (CE->isCast()) {
803 printConstant(CE->getOperand(0));
804 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
805 switch (CE->getOpcode()) {
806 default: assert(0 && "Invalid cast opcode");
807 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
808 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
809 case Instruction::SExt: Out << "Instruction::SExt"; break;
810 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
811 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
812 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
813 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
814 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
815 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
816 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
817 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
818 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
820 Out << ", " << getCppName(CE->getOperand(0)) << ", "
821 << getCppName(CE->getType()) << ");";
823 unsigned N = CE->getNumOperands();
824 for (unsigned i = 0; i < N; ++i ) {
825 printConstant(CE->getOperand(i));
827 Out << "Constant* " << constName << " = ConstantExpr::";
828 switch (CE->getOpcode()) {
829 case Instruction::Add: Out << "getAdd("; break;
830 case Instruction::Sub: Out << "getSub("; break;
831 case Instruction::Mul: Out << "getMul("; break;
832 case Instruction::UDiv: Out << "getUDiv("; break;
833 case Instruction::SDiv: Out << "getSDiv("; break;
834 case Instruction::FDiv: Out << "getFDiv("; break;
835 case Instruction::URem: Out << "getURem("; break;
836 case Instruction::SRem: Out << "getSRem("; break;
837 case Instruction::FRem: Out << "getFRem("; break;
838 case Instruction::And: Out << "getAnd("; break;
839 case Instruction::Or: Out << "getOr("; break;
840 case Instruction::Xor: Out << "getXor("; break;
841 case Instruction::ICmp:
842 Out << "getICmp(ICmpInst::ICMP_";
843 switch (CE->getPredicate()) {
844 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
845 case ICmpInst::ICMP_NE: Out << "NE"; break;
846 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
847 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
848 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
849 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
850 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
851 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
852 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
853 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
854 default: error("Invalid ICmp Predicate");
857 case Instruction::FCmp:
858 Out << "getFCmp(FCmpInst::FCMP_";
859 switch (CE->getPredicate()) {
860 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
861 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
862 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
863 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
864 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
865 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
866 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
867 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
868 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
869 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
870 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
871 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
872 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
873 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
874 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
875 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
876 default: error("Invalid FCmp Predicate");
879 case Instruction::Shl: Out << "getShl("; break;
880 case Instruction::LShr: Out << "getLShr("; break;
881 case Instruction::AShr: Out << "getAShr("; break;
882 case Instruction::Select: Out << "getSelect("; break;
883 case Instruction::ExtractElement: Out << "getExtractElement("; break;
884 case Instruction::InsertElement: Out << "getInsertElement("; break;
885 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
887 error("Invalid constant expression");
890 Out << getCppName(CE->getOperand(0));
891 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
892 Out << ", " << getCppName(CE->getOperand(i));
896 error("Bad Constant");
897 Out << "Constant* " << constName << " = 0; ";
903 CppWriter::printConstants(const Module* M) {
904 // Traverse all the global variables looking for constant initializers
905 for (Module::const_global_iterator I = TheModule->global_begin(),
906 E = TheModule->global_end(); I != E; ++I)
907 if (I->hasInitializer())
908 printConstant(I->getInitializer());
910 // Traverse the LLVM functions looking for constants
911 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
913 // Add all of the basic blocks and instructions
914 for (Function::const_iterator BB = FI->begin(),
915 E = FI->end(); BB != E; ++BB) {
916 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
918 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
919 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
928 void CppWriter::printVariableUses(const GlobalVariable *GV) {
929 nl(Out) << "// Type Definitions";
931 printType(GV->getType());
932 if (GV->hasInitializer()) {
933 Constant* Init = GV->getInitializer();
934 printType(Init->getType());
935 if (Function* F = dyn_cast<Function>(Init)) {
936 nl(Out)<< "/ Function Declarations"; nl(Out);
937 printFunctionHead(F);
938 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
939 nl(Out) << "// Global Variable Declarations"; nl(Out);
940 printVariableHead(gv);
942 nl(Out) << "// Constant Definitions"; nl(Out);
945 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
946 nl(Out) << "// Global Variable Definitions"; nl(Out);
947 printVariableBody(gv);
952 void CppWriter::printVariableHead(const GlobalVariable *GV) {
953 nl(Out) << "GlobalVariable* " << getCppName(GV);
955 Out << " = mod->getGlobalVariable(";
956 printEscapedString(GV->getName());
957 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
958 nl(Out) << "if (!" << getCppName(GV) << ") {";
959 in(); nl(Out) << getCppName(GV);
961 Out << " = new GlobalVariable(";
962 nl(Out) << "/*Type=*/";
963 printCppName(GV->getType()->getElementType());
965 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
967 nl(Out) << "/*Linkage=*/";
968 printLinkageType(GV->getLinkage());
970 nl(Out) << "/*Initializer=*/0, ";
971 if (GV->hasInitializer()) {
972 Out << "// has initializer, specified below";
974 nl(Out) << "/*Name=*/\"";
975 printEscapedString(GV->getName());
980 if (GV->hasSection()) {
982 Out << "->setSection(\"";
983 printEscapedString(GV->getSection());
987 if (GV->getAlignment()) {
989 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
993 out(); Out << "}"; nl(Out);
998 CppWriter::printVariableBody(const GlobalVariable *GV) {
999 if (GV->hasInitializer()) {
1001 Out << "->setInitializer(";
1002 //if (!isa<GlobalValue(GV->getInitializer()))
1004 Out << getCppName(GV->getInitializer()) << ");";
1010 CppWriter::getOpName(Value* V) {
1011 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1012 return getCppName(V);
1014 // See if its alread in the map of forward references, if so just return the
1015 // name we already set up for it
1016 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1017 if (I != ForwardRefs.end())
1020 // This is a new forward reference. Generate a unique name for it
1021 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1023 // Yes, this is a hack. An Argument is the smallest instantiable value that
1024 // we can make as a placeholder for the real value. We'll replace these
1025 // Argument instances later.
1026 Out << "Argument* " << result << " = new Argument("
1027 << getCppName(V->getType()) << ");";
1029 ForwardRefs[V] = result;
1033 // printInstruction - This member is called for each Instruction in a function.
1035 CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
1036 std::string iName(getCppName(I));
1038 // Before we emit this instruction, we need to take care of generating any
1039 // forward references. So, we get the names of all the operands in advance
1040 std::string* opNames = new std::string[I->getNumOperands()];
1041 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1042 opNames[i] = getOpName(I->getOperand(i));
1045 switch (I->getOpcode()) {
1046 case Instruction::Ret: {
1047 const ReturnInst* ret = cast<ReturnInst>(I);
1048 Out << "new ReturnInst("
1049 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1052 case Instruction::Br: {
1053 const BranchInst* br = cast<BranchInst>(I);
1054 Out << "new BranchInst(" ;
1055 if (br->getNumOperands() == 3 ) {
1056 Out << opNames[0] << ", "
1057 << opNames[1] << ", "
1058 << opNames[2] << ", ";
1060 } else if (br->getNumOperands() == 1) {
1061 Out << opNames[0] << ", ";
1063 error("Branch with 2 operands?");
1065 Out << bbname << ");";
1068 case Instruction::Switch: {
1069 const SwitchInst* sw = cast<SwitchInst>(I);
1070 Out << "SwitchInst* " << iName << " = new SwitchInst("
1071 << opNames[0] << ", "
1072 << opNames[1] << ", "
1073 << sw->getNumCases() << ", " << bbname << ");";
1075 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1076 Out << iName << "->addCase("
1077 << opNames[i] << ", "
1078 << opNames[i+1] << ");";
1083 case Instruction::Invoke: {
1084 const InvokeInst* inv = cast<InvokeInst>(I);
1085 Out << "std::vector<Value*> " << iName << "_params;";
1087 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1088 Out << iName << "_params.push_back("
1089 << opNames[i] << ");";
1092 Out << "InvokeInst *" << iName << " = new InvokeInst("
1093 << opNames[0] << ", "
1094 << opNames[1] << ", "
1095 << opNames[2] << ", "
1096 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1097 printEscapedString(inv->getName());
1098 Out << "\", " << bbname << ");";
1099 nl(Out) << iName << "->setCallingConv(";
1100 printCallingConv(inv->getCallingConv());
1104 case Instruction::Unwind: {
1105 Out << "new UnwindInst("
1109 case Instruction::Unreachable:{
1110 Out << "new UnreachableInst("
1114 case Instruction::Add:
1115 case Instruction::Sub:
1116 case Instruction::Mul:
1117 case Instruction::UDiv:
1118 case Instruction::SDiv:
1119 case Instruction::FDiv:
1120 case Instruction::URem:
1121 case Instruction::SRem:
1122 case Instruction::FRem:
1123 case Instruction::And:
1124 case Instruction::Or:
1125 case Instruction::Xor:
1126 case Instruction::Shl:
1127 case Instruction::LShr:
1128 case Instruction::AShr:{
1129 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1130 switch (I->getOpcode()) {
1131 case Instruction::Add: Out << "Instruction::Add"; break;
1132 case Instruction::Sub: Out << "Instruction::Sub"; break;
1133 case Instruction::Mul: Out << "Instruction::Mul"; break;
1134 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1135 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1136 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1137 case Instruction::URem:Out << "Instruction::URem"; break;
1138 case Instruction::SRem:Out << "Instruction::SRem"; break;
1139 case Instruction::FRem:Out << "Instruction::FRem"; break;
1140 case Instruction::And: Out << "Instruction::And"; break;
1141 case Instruction::Or: Out << "Instruction::Or"; break;
1142 case Instruction::Xor: Out << "Instruction::Xor"; break;
1143 case Instruction::Shl: Out << "Instruction::Shl"; break;
1144 case Instruction::LShr:Out << "Instruction::LShr"; break;
1145 case Instruction::AShr:Out << "Instruction::AShr"; break;
1146 default: Out << "Instruction::BadOpCode"; break;
1148 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1149 printEscapedString(I->getName());
1150 Out << "\", " << bbname << ");";
1153 case Instruction::FCmp: {
1154 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1155 switch (cast<FCmpInst>(I)->getPredicate()) {
1156 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1157 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1158 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1159 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1160 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1161 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1162 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1163 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1164 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1165 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1166 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1167 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1168 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1169 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1170 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1171 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1172 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1174 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1175 printEscapedString(I->getName());
1176 Out << "\", " << bbname << ");";
1179 case Instruction::ICmp: {
1180 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1181 switch (cast<ICmpInst>(I)->getPredicate()) {
1182 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1183 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1184 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1185 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1186 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1187 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1188 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1189 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1190 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1191 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1192 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1194 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1195 printEscapedString(I->getName());
1196 Out << "\", " << bbname << ");";
1199 case Instruction::Malloc: {
1200 const MallocInst* mallocI = cast<MallocInst>(I);
1201 Out << "MallocInst* " << iName << " = new MallocInst("
1202 << getCppName(mallocI->getAllocatedType()) << ", ";
1203 if (mallocI->isArrayAllocation())
1204 Out << opNames[0] << ", " ;
1206 printEscapedString(mallocI->getName());
1207 Out << "\", " << bbname << ");";
1208 if (mallocI->getAlignment())
1209 nl(Out) << iName << "->setAlignment("
1210 << mallocI->getAlignment() << ");";
1213 case Instruction::Free: {
1214 Out << "FreeInst* " << iName << " = new FreeInst("
1215 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1218 case Instruction::Alloca: {
1219 const AllocaInst* allocaI = cast<AllocaInst>(I);
1220 Out << "AllocaInst* " << iName << " = new AllocaInst("
1221 << getCppName(allocaI->getAllocatedType()) << ", ";
1222 if (allocaI->isArrayAllocation())
1223 Out << opNames[0] << ", ";
1225 printEscapedString(allocaI->getName());
1226 Out << "\", " << bbname << ");";
1227 if (allocaI->getAlignment())
1228 nl(Out) << iName << "->setAlignment("
1229 << allocaI->getAlignment() << ");";
1232 case Instruction::Load:{
1233 const LoadInst* load = cast<LoadInst>(I);
1234 Out << "LoadInst* " << iName << " = new LoadInst("
1235 << opNames[0] << ", \"";
1236 printEscapedString(load->getName());
1237 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1238 << ", " << bbname << ");";
1241 case Instruction::Store: {
1242 const StoreInst* store = cast<StoreInst>(I);
1243 Out << "StoreInst* " << iName << " = new StoreInst("
1244 << opNames[0] << ", "
1245 << opNames[1] << ", "
1246 << (store->isVolatile() ? "true" : "false")
1247 << ", " << bbname << ");";
1250 case Instruction::GetElementPtr: {
1251 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1252 if (gep->getNumOperands() <= 2) {
1253 Out << "GetElementPtrInst* " << iName << " = new GetElementPtrInst("
1255 if (gep->getNumOperands() == 2)
1256 Out << ", " << opNames[1];
1258 Out << "std::vector<Value*> " << iName << "_indices;";
1260 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1261 Out << iName << "_indices.push_back("
1262 << opNames[i] << ");";
1265 Out << "Instruction* " << iName << " = new GetElementPtrInst("
1266 << opNames[0] << ", " << iName << "_indices.begin(), "
1267 << iName << "_indices.end()";
1270 printEscapedString(gep->getName());
1271 Out << "\", " << bbname << ");";
1274 case Instruction::PHI: {
1275 const PHINode* phi = cast<PHINode>(I);
1277 Out << "PHINode* " << iName << " = new PHINode("
1278 << getCppName(phi->getType()) << ", \"";
1279 printEscapedString(phi->getName());
1280 Out << "\", " << bbname << ");";
1281 nl(Out) << iName << "->reserveOperandSpace("
1282 << phi->getNumIncomingValues()
1285 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1286 Out << iName << "->addIncoming("
1287 << opNames[i] << ", " << opNames[i+1] << ");";
1292 case Instruction::Trunc:
1293 case Instruction::ZExt:
1294 case Instruction::SExt:
1295 case Instruction::FPTrunc:
1296 case Instruction::FPExt:
1297 case Instruction::FPToUI:
1298 case Instruction::FPToSI:
1299 case Instruction::UIToFP:
1300 case Instruction::SIToFP:
1301 case Instruction::PtrToInt:
1302 case Instruction::IntToPtr:
1303 case Instruction::BitCast: {
1304 const CastInst* cst = cast<CastInst>(I);
1305 Out << "CastInst* " << iName << " = new ";
1306 switch (I->getOpcode()) {
1307 case Instruction::Trunc: Out << "TruncInst"; break;
1308 case Instruction::ZExt: Out << "ZExtInst"; break;
1309 case Instruction::SExt: Out << "SExtInst"; break;
1310 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1311 case Instruction::FPExt: Out << "FPExtInst"; break;
1312 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1313 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1314 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1315 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1316 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1317 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1318 case Instruction::BitCast: Out << "BitCastInst"; break;
1319 default: assert(!"Unreachable"); break;
1321 Out << "(" << opNames[0] << ", "
1322 << getCppName(cst->getType()) << ", \"";
1323 printEscapedString(cst->getName());
1324 Out << "\", " << bbname << ");";
1327 case Instruction::Call:{
1328 const CallInst* call = cast<CallInst>(I);
1329 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1330 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1331 << getCppName(ila->getFunctionType()) << ", \""
1332 << ila->getAsmString() << "\", \""
1333 << ila->getConstraintString() << "\","
1334 << (ila->hasSideEffects() ? "true" : "false") << ");";
1337 if (call->getNumOperands() > 2) {
1338 Out << "std::vector<Value*> " << iName << "_params;";
1340 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1341 Out << iName << "_params.push_back(" << opNames[i] << ");";
1344 Out << "CallInst* " << iName << " = new CallInst("
1345 << opNames[0] << ", " << iName << "_params.begin(), "
1346 << iName << "_params.end(), \"";
1347 } else if (call->getNumOperands() == 2) {
1348 Out << "CallInst* " << iName << " = new CallInst("
1349 << opNames[0] << ", " << opNames[1] << ", \"";
1351 Out << "CallInst* " << iName << " = new CallInst(" << opNames[0]
1354 printEscapedString(call->getName());
1355 Out << "\", " << bbname << ");";
1356 nl(Out) << iName << "->setCallingConv(";
1357 printCallingConv(call->getCallingConv());
1359 nl(Out) << iName << "->setTailCall("
1360 << (call->isTailCall() ? "true":"false");
1364 case Instruction::Select: {
1365 const SelectInst* sel = cast<SelectInst>(I);
1366 Out << "SelectInst* " << getCppName(sel) << " = new SelectInst(";
1367 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1368 printEscapedString(sel->getName());
1369 Out << "\", " << bbname << ");";
1372 case Instruction::UserOp1:
1374 case Instruction::UserOp2: {
1375 /// FIXME: What should be done here?
1378 case Instruction::VAArg: {
1379 const VAArgInst* va = cast<VAArgInst>(I);
1380 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1381 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1382 printEscapedString(va->getName());
1383 Out << "\", " << bbname << ");";
1386 case Instruction::ExtractElement: {
1387 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1388 Out << "ExtractElementInst* " << getCppName(eei)
1389 << " = new ExtractElementInst(" << opNames[0]
1390 << ", " << opNames[1] << ", \"";
1391 printEscapedString(eei->getName());
1392 Out << "\", " << bbname << ");";
1395 case Instruction::InsertElement: {
1396 const InsertElementInst* iei = cast<InsertElementInst>(I);
1397 Out << "InsertElementInst* " << getCppName(iei)
1398 << " = new InsertElementInst(" << opNames[0]
1399 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1400 printEscapedString(iei->getName());
1401 Out << "\", " << bbname << ");";
1404 case Instruction::ShuffleVector: {
1405 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1406 Out << "ShuffleVectorInst* " << getCppName(svi)
1407 << " = new ShuffleVectorInst(" << opNames[0]
1408 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1409 printEscapedString(svi->getName());
1410 Out << "\", " << bbname << ");";
1414 DefinedValues.insert(I);
1419 // Print out the types, constants and declarations needed by one function
1420 void CppWriter::printFunctionUses(const Function* F) {
1422 nl(Out) << "// Type Definitions"; nl(Out);
1424 // Print the function's return type
1425 printType(F->getReturnType());
1427 // Print the function's function type
1428 printType(F->getFunctionType());
1430 // Print the types of each of the function's arguments
1431 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1433 printType(AI->getType());
1437 // Print type definitions for every type referenced by an instruction and
1438 // make a note of any global values or constants that are referenced
1439 SmallPtrSet<GlobalValue*,64> gvs;
1440 SmallPtrSet<Constant*,64> consts;
1441 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1442 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1444 // Print the type of the instruction itself
1445 printType(I->getType());
1447 // Print the type of each of the instruction's operands
1448 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1449 Value* operand = I->getOperand(i);
1450 printType(operand->getType());
1452 // If the operand references a GVal or Constant, make a note of it
1453 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1455 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1456 if (GVar->hasInitializer())
1457 consts.insert(GVar->getInitializer());
1458 } else if (Constant* C = dyn_cast<Constant>(operand))
1464 // Print the function declarations for any functions encountered
1465 nl(Out) << "// Function Declarations"; nl(Out);
1466 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1468 if (Function* Fun = dyn_cast<Function>(*I)) {
1469 if (!is_inline || Fun != F)
1470 printFunctionHead(Fun);
1474 // Print the global variable declarations for any variables encountered
1475 nl(Out) << "// Global Variable Declarations"; nl(Out);
1476 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1478 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1479 printVariableHead(F);
1482 // Print the constants found
1483 nl(Out) << "// Constant Definitions"; nl(Out);
1484 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(), E = consts.end();
1489 // Process the global variables definitions now that all the constants have
1490 // been emitted. These definitions just couple the gvars with their constant
1492 nl(Out) << "// Global Variable Definitions"; nl(Out);
1493 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1495 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1496 printVariableBody(GV);
1500 void CppWriter::printFunctionHead(const Function* F) {
1501 nl(Out) << "Function* " << getCppName(F);
1503 Out << " = mod->getFunction(\"";
1504 printEscapedString(F->getName());
1505 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1506 nl(Out) << "if (!" << getCppName(F) << ") {";
1507 nl(Out) << getCppName(F);
1509 Out<< " = new Function(";
1510 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1511 nl(Out) << "/*Linkage=*/";
1512 printLinkageType(F->getLinkage());
1514 nl(Out) << "/*Name=*/\"";
1515 printEscapedString(F->getName());
1516 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1519 Out << "->setCallingConv(";
1520 printCallingConv(F->getCallingConv());
1523 if (F->hasSection()) {
1525 Out << "->setSection(\"" << F->getSection() << "\");";
1528 if (F->getAlignment()) {
1530 Out << "->setAlignment(" << F->getAlignment() << ");";
1539 void CppWriter::printFunctionBody(const Function *F) {
1540 if (F->isDeclaration())
1541 return; // external functions have no bodies.
1543 // Clear the DefinedValues and ForwardRefs maps because we can't have
1544 // cross-function forward refs
1545 ForwardRefs.clear();
1546 DefinedValues.clear();
1548 // Create all the argument values
1550 if (!F->arg_empty()) {
1551 Out << "Function::arg_iterator args = " << getCppName(F)
1552 << "->arg_begin();";
1555 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1557 Out << "Value* " << getCppName(AI) << " = args++;";
1559 if (AI->hasName()) {
1560 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1566 // Create all the basic blocks
1568 for (Function::const_iterator BI = F->begin(), BE = F->end();
1570 std::string bbname(getCppName(BI));
1571 Out << "BasicBlock* " << bbname << " = new BasicBlock(\"";
1573 printEscapedString(BI->getName());
1574 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1578 // Output all of its basic blocks... for the function
1579 for (Function::const_iterator BI = F->begin(), BE = F->end();
1581 std::string bbname(getCppName(BI));
1582 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1585 // Output all of the instructions in the basic block...
1586 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1588 printInstruction(I,bbname);
1592 // Loop over the ForwardRefs and resolve them now that all instructions
1594 if (!ForwardRefs.empty()) {
1595 nl(Out) << "// Resolve Forward References";
1599 while (!ForwardRefs.empty()) {
1600 ForwardRefMap::iterator I = ForwardRefs.begin();
1601 Out << I->second << "->replaceAllUsesWith("
1602 << getCppName(I->first) << "); delete " << I->second << ";";
1604 ForwardRefs.erase(I);
1608 void CppWriter::printInline(const std::string& fname, const std::string& func) {
1609 const Function* F = TheModule->getFunction(func);
1611 error(std::string("Function '") + func + "' not found in input module");
1614 if (F->isDeclaration()) {
1615 error(std::string("Function '") + func + "' is external!");
1618 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1620 unsigned arg_count = 1;
1621 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1623 Out << ", Value* arg_" << arg_count;
1628 printFunctionUses(F);
1629 printFunctionBody(F);
1631 Out << "return " << getCppName(F->begin()) << ";";
1636 void CppWriter::printModuleBody() {
1637 // Print out all the type definitions
1638 nl(Out) << "// Type Definitions"; nl(Out);
1639 printTypes(TheModule);
1641 // Functions can call each other and global variables can reference them so
1642 // define all the functions first before emitting their function bodies.
1643 nl(Out) << "// Function Declarations"; nl(Out);
1644 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1646 printFunctionHead(I);
1648 // Process the global variables declarations. We can't initialze them until
1649 // after the constants are printed so just print a header for each global
1650 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1651 for (Module::const_global_iterator I = TheModule->global_begin(),
1652 E = TheModule->global_end(); I != E; ++I) {
1653 printVariableHead(I);
1656 // Print out all the constants definitions. Constants don't recurse except
1657 // through GlobalValues. All GlobalValues have been declared at this point
1658 // so we can proceed to generate the constants.
1659 nl(Out) << "// Constant Definitions"; nl(Out);
1660 printConstants(TheModule);
1662 // Process the global variables definitions now that all the constants have
1663 // been emitted. These definitions just couple the gvars with their constant
1665 nl(Out) << "// Global Variable Definitions"; nl(Out);
1666 for (Module::const_global_iterator I = TheModule->global_begin(),
1667 E = TheModule->global_end(); I != E; ++I) {
1668 printVariableBody(I);
1671 // Finally, we can safely put out all of the function bodies.
1672 nl(Out) << "// Function Definitions"; nl(Out);
1673 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1675 if (!I->isDeclaration()) {
1676 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1680 printFunctionBody(I);
1687 void CppWriter::printProgram(
1688 const std::string& fname,
1689 const std::string& mName
1691 Out << "#include <llvm/Module.h>\n";
1692 Out << "#include <llvm/DerivedTypes.h>\n";
1693 Out << "#include <llvm/Constants.h>\n";
1694 Out << "#include <llvm/GlobalVariable.h>\n";
1695 Out << "#include <llvm/Function.h>\n";
1696 Out << "#include <llvm/CallingConv.h>\n";
1697 Out << "#include <llvm/BasicBlock.h>\n";
1698 Out << "#include <llvm/Instructions.h>\n";
1699 Out << "#include <llvm/InlineAsm.h>\n";
1700 Out << "#include <llvm/ParameterAttributes.h>\n";
1701 Out << "#include <llvm/Support/MathExtras.h>\n";
1702 Out << "#include <llvm/Pass.h>\n";
1703 Out << "#include <llvm/PassManager.h>\n";
1704 Out << "#include <llvm/Analysis/Verifier.h>\n";
1705 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1706 Out << "#include <algorithm>\n";
1707 Out << "#include <iostream>\n\n";
1708 Out << "using namespace llvm;\n\n";
1709 Out << "Module* " << fname << "();\n\n";
1710 Out << "int main(int argc, char**argv) {\n";
1711 Out << " Module* Mod = " << fname << "();\n";
1712 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1713 Out << " std::cerr.flush();\n";
1714 Out << " std::cout.flush();\n";
1715 Out << " PassManager PM;\n";
1716 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1717 Out << " PM.run(*Mod);\n";
1718 Out << " return 0;\n";
1720 printModule(fname,mName);
1723 void CppWriter::printModule(
1724 const std::string& fname,
1725 const std::string& mName
1727 nl(Out) << "Module* " << fname << "() {";
1728 nl(Out,1) << "// Module Construction";
1729 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1730 if (!TheModule->getTargetTriple().empty()) {
1731 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1733 if (!TheModule->getTargetTriple().empty()) {
1734 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1738 if (!TheModule->getModuleInlineAsm().empty()) {
1739 nl(Out) << "mod->setModuleInlineAsm(\"";
1740 printEscapedString(TheModule->getModuleInlineAsm());
1745 // Loop over the dependent libraries and emit them.
1746 Module::lib_iterator LI = TheModule->lib_begin();
1747 Module::lib_iterator LE = TheModule->lib_end();
1749 Out << "mod->addLibrary(\"" << *LI << "\");";
1754 nl(Out) << "return mod;";
1759 void CppWriter::printContents(
1760 const std::string& fname, // Name of generated function
1761 const std::string& mName // Name of module generated module
1763 Out << "\nModule* " << fname << "(Module *mod) {\n";
1764 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1766 Out << "\nreturn mod;\n";
1770 void CppWriter::printFunction(
1771 const std::string& fname, // Name of generated function
1772 const std::string& funcName // Name of function to generate
1774 const Function* F = TheModule->getFunction(funcName);
1776 error(std::string("Function '") + funcName + "' not found in input module");
1779 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1780 printFunctionUses(F);
1781 printFunctionHead(F);
1782 printFunctionBody(F);
1783 Out << "return " << getCppName(F) << ";\n";
1787 void CppWriter::printVariable(
1788 const std::string& fname, /// Name of generated function
1789 const std::string& varName // Name of variable to generate
1791 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1794 error(std::string("Variable '") + varName + "' not found in input module");
1797 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1798 printVariableUses(GV);
1799 printVariableHead(GV);
1800 printVariableBody(GV);
1801 Out << "return " << getCppName(GV) << ";\n";
1805 void CppWriter::printType(
1806 const std::string& fname, /// Name of generated function
1807 const std::string& typeName // Name of type to generate
1809 const Type* Ty = TheModule->getTypeByName(typeName);
1811 error(std::string("Type '") + typeName + "' not found in input module");
1814 Out << "\nType* " << fname << "(Module *mod) {\n";
1816 Out << "return " << getCppName(Ty) << ";\n";
1820 } // end anonymous llvm
1824 void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1825 // Initialize a CppWriter for us to use
1826 CppWriter W(o, mod);
1829 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1831 // Get the name of the function we're supposed to generate
1832 std::string fname = FuncName.getValue();
1834 // Get the name of the thing we are to generate
1835 std::string tgtname = NameToGenerate.getValue();
1836 if (GenerationType == GenModule ||
1837 GenerationType == GenContents ||
1838 GenerationType == GenProgram) {
1839 if (tgtname == "!bad!") {
1840 if (mod->getModuleIdentifier() == "-")
1841 tgtname = "<stdin>";
1843 tgtname = mod->getModuleIdentifier();
1845 } else if (tgtname == "!bad!") {
1846 W.error("You must use the -for option with -gen-{function,variable,type}");
1849 switch (WhatToGenerate(GenerationType)) {
1852 fname = "makeLLVMModule";
1853 W.printProgram(fname,tgtname);
1857 fname = "makeLLVMModule";
1858 W.printModule(fname,tgtname);
1862 fname = "makeLLVMModuleContents";
1863 W.printContents(fname,tgtname);
1867 fname = "makeLLVMFunction";
1868 W.printFunction(fname,tgtname);
1872 fname = "makeLLVMInline";
1873 W.printInline(fname,tgtname);
1877 fname = "makeLLVMVariable";
1878 W.printVariable(fname,tgtname);
1882 fname = "makeLLVMType";
1883 W.printType(fname,tgtname);
1886 W.error("Invalid generation option");