1 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the writing of the LLVM IR as a set of C++ calls to the
11 // LLVM IR interface. The input module is assumed to be verified.
13 //===----------------------------------------------------------------------===//
15 #include "CPPTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instruction.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Target/TargetRegistry.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Config/config.h"
39 static cl::opt<std::string>
40 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
41 cl::value_desc("function name"));
54 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
55 cl::desc("Choose what kind of output to generate"),
58 clEnumValN(GenProgram, "program", "Generate a complete program"),
59 clEnumValN(GenModule, "module", "Generate a module definition"),
60 clEnumValN(GenContents, "contents", "Generate contents of a module"),
61 clEnumValN(GenFunction, "function", "Generate a function definition"),
62 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
63 clEnumValN(GenInline, "inline", "Generate an inline function"),
64 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
65 clEnumValN(GenType, "type", "Generate a type definition"),
70 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
71 cl::desc("Specify the name of the thing to generate"),
74 extern "C" void LLVMInitializeCppBackendTarget() {
75 // Register the target.
76 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
79 extern "C" void LLVMInitializeCppBackendMCInstrInfo() {
80 RegisterMCInstrInfo<MCInstrInfo> X(TheCppBackendTarget);
83 extern "C" void LLVMInitializeCppBackendMCSubtargetInfo() {
84 RegisterMCSubtargetInfo<MCSubtargetInfo> X(TheCppBackendTarget);
88 typedef std::vector<const Type*> TypeList;
89 typedef std::map<const Type*,std::string> TypeMap;
90 typedef std::map<const Value*,std::string> ValueMap;
91 typedef std::set<std::string> NameSet;
92 typedef std::set<const Type*> TypeSet;
93 typedef std::set<const Value*> ValueSet;
94 typedef std::map<const Value*,std::string> ForwardRefMap;
96 /// CppWriter - This class is the main chunk of code that converts an LLVM
97 /// module to a C++ translation unit.
98 class CppWriter : public ModulePass {
99 formatted_raw_ostream &Out;
100 const Module *TheModule;
105 TypeSet DefinedTypes;
106 ValueSet DefinedValues;
107 ForwardRefMap ForwardRefs;
109 unsigned indent_level;
113 explicit CppWriter(formatted_raw_ostream &o) :
114 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
116 virtual const char *getPassName() const { return "C++ backend"; }
118 bool runOnModule(Module &M);
120 void printProgram(const std::string& fname, const std::string& modName );
121 void printModule(const std::string& fname, const std::string& modName );
122 void printContents(const std::string& fname, const std::string& modName );
123 void printFunction(const std::string& fname, const std::string& funcName );
124 void printFunctions();
125 void printInline(const std::string& fname, const std::string& funcName );
126 void printVariable(const std::string& fname, const std::string& varName );
127 void printType(const std::string& fname, const std::string& typeName );
129 void error(const std::string& msg);
132 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
133 inline void in() { indent_level++; }
134 inline void out() { if (indent_level >0) indent_level--; }
137 void printLinkageType(GlobalValue::LinkageTypes LT);
138 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
139 void printCallingConv(CallingConv::ID cc);
140 void printEscapedString(const std::string& str);
141 void printCFP(const ConstantFP* CFP);
143 std::string getCppName(const Type* val);
144 inline void printCppName(const Type* val);
146 std::string getCppName(const Value* val);
147 inline void printCppName(const Value* val);
149 void printAttributes(const AttrListPtr &PAL, const std::string &name);
150 void printType(const Type* Ty);
151 void printTypes(const Module* M);
153 void printConstant(const Constant *CPV);
154 void printConstants(const Module* M);
156 void printVariableUses(const GlobalVariable *GV);
157 void printVariableHead(const GlobalVariable *GV);
158 void printVariableBody(const GlobalVariable *GV);
160 void printFunctionUses(const Function *F);
161 void printFunctionHead(const Function *F);
162 void printFunctionBody(const Function *F);
163 void printInstruction(const Instruction *I, const std::string& bbname);
164 std::string getOpName(Value*);
166 void printModuleBody();
168 } // end anonymous namespace.
170 formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
172 if (delta >= 0 || indent_level >= unsigned(-delta))
173 indent_level += delta;
174 Out.indent(indent_level);
178 static inline void sanitize(std::string &str) {
179 for (size_t i = 0; i < str.length(); ++i)
180 if (!isalnum(str[i]) && str[i] != '_')
184 static std::string getTypePrefix(const Type *Ty) {
185 switch (Ty->getTypeID()) {
186 case Type::VoidTyID: return "void_";
187 case Type::IntegerTyID:
188 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
189 case Type::FloatTyID: return "float_";
190 case Type::DoubleTyID: return "double_";
191 case Type::LabelTyID: return "label_";
192 case Type::FunctionTyID: return "func_";
193 case Type::StructTyID: return "struct_";
194 case Type::ArrayTyID: return "array_";
195 case Type::PointerTyID: return "ptr_";
196 case Type::VectorTyID: return "packed_";
197 default: return "other_";
202 void CppWriter::error(const std::string& msg) {
203 report_fatal_error(msg);
206 // printCFP - Print a floating point constant .. very carefully :)
207 // This makes sure that conversion to/from floating yields the same binary
208 // result so that we don't lose precision.
209 void CppWriter::printCFP(const ConstantFP *CFP) {
211 APFloat APF = APFloat(CFP->getValueAPF()); // copy
212 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
213 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
214 Out << "ConstantFP::get(mod->getContext(), ";
218 sprintf(Buffer, "%A", APF.convertToDouble());
219 if ((!strncmp(Buffer, "0x", 2) ||
220 !strncmp(Buffer, "-0x", 3) ||
221 !strncmp(Buffer, "+0x", 3)) &&
222 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
223 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
224 Out << "BitsToDouble(" << Buffer << ")";
226 Out << "BitsToFloat((float)" << Buffer << ")";
230 std::string StrVal = ftostr(CFP->getValueAPF());
232 while (StrVal[0] == ' ')
233 StrVal.erase(StrVal.begin());
235 // Check to make sure that the stringized number is not some string like
236 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
237 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
238 ((StrVal[0] == '-' || StrVal[0] == '+') &&
239 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
240 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
241 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
244 Out << StrVal << "f";
245 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
246 Out << "BitsToDouble(0x"
247 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
248 << "ULL) /* " << StrVal << " */";
250 Out << "BitsToFloat(0x"
251 << utohexstr((uint32_t)CFP->getValueAPF().
252 bitcastToAPInt().getZExtValue())
253 << "U) /* " << StrVal << " */";
261 void CppWriter::printCallingConv(CallingConv::ID cc){
262 // Print the calling convention.
264 case CallingConv::C: Out << "CallingConv::C"; break;
265 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
266 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
267 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
268 default: Out << cc; break;
272 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
274 case GlobalValue::InternalLinkage:
275 Out << "GlobalValue::InternalLinkage"; break;
276 case GlobalValue::PrivateLinkage:
277 Out << "GlobalValue::PrivateLinkage"; break;
278 case GlobalValue::LinkerPrivateLinkage:
279 Out << "GlobalValue::LinkerPrivateLinkage"; break;
280 case GlobalValue::LinkerPrivateWeakLinkage:
281 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
282 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
283 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
284 case GlobalValue::AvailableExternallyLinkage:
285 Out << "GlobalValue::AvailableExternallyLinkage "; break;
286 case GlobalValue::LinkOnceAnyLinkage:
287 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
288 case GlobalValue::LinkOnceODRLinkage:
289 Out << "GlobalValue::LinkOnceODRLinkage "; break;
290 case GlobalValue::WeakAnyLinkage:
291 Out << "GlobalValue::WeakAnyLinkage"; break;
292 case GlobalValue::WeakODRLinkage:
293 Out << "GlobalValue::WeakODRLinkage"; break;
294 case GlobalValue::AppendingLinkage:
295 Out << "GlobalValue::AppendingLinkage"; break;
296 case GlobalValue::ExternalLinkage:
297 Out << "GlobalValue::ExternalLinkage"; break;
298 case GlobalValue::DLLImportLinkage:
299 Out << "GlobalValue::DLLImportLinkage"; break;
300 case GlobalValue::DLLExportLinkage:
301 Out << "GlobalValue::DLLExportLinkage"; break;
302 case GlobalValue::ExternalWeakLinkage:
303 Out << "GlobalValue::ExternalWeakLinkage"; break;
304 case GlobalValue::CommonLinkage:
305 Out << "GlobalValue::CommonLinkage"; break;
309 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
311 default: llvm_unreachable("Unknown GVar visibility");
312 case GlobalValue::DefaultVisibility:
313 Out << "GlobalValue::DefaultVisibility";
315 case GlobalValue::HiddenVisibility:
316 Out << "GlobalValue::HiddenVisibility";
318 case GlobalValue::ProtectedVisibility:
319 Out << "GlobalValue::ProtectedVisibility";
324 // printEscapedString - Print each character of the specified string, escaping
325 // it if it is not printable or if it is an escape char.
326 void CppWriter::printEscapedString(const std::string &Str) {
327 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
328 unsigned char C = Str[i];
329 if (isprint(C) && C != '"' && C != '\\') {
333 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
334 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
339 std::string CppWriter::getCppName(const Type* Ty) {
340 // First, handle the primitive types .. easy
341 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
342 switch (Ty->getTypeID()) {
343 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
344 case Type::IntegerTyID: {
345 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
346 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
348 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
349 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
350 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
351 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
352 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
354 error("Invalid primitive type");
357 // shouldn't be returned, but make it sensible
358 return "Type::getVoidTy(mod->getContext())";
361 // Now, see if we've seen the type before and return that
362 TypeMap::iterator I = TypeNames.find(Ty);
363 if (I != TypeNames.end())
366 // Okay, let's build a new name for this type. Start with a prefix
367 const char* prefix = 0;
368 switch (Ty->getTypeID()) {
369 case Type::FunctionTyID: prefix = "FuncTy_"; break;
370 case Type::StructTyID: prefix = "StructTy_"; break;
371 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
372 case Type::PointerTyID: prefix = "PointerTy_"; break;
373 case Type::VectorTyID: prefix = "VectorTy_"; break;
374 default: prefix = "OtherTy_"; break; // prevent breakage
377 // See if the type has a name in the symboltable and build accordingly
379 if (const StructType *STy = dyn_cast<StructType>(Ty))
381 name = STy->getName();
384 name = utostr(uniqueNum++);
386 name = std::string(prefix) + name;
390 return TypeNames[Ty] = name;
393 void CppWriter::printCppName(const Type* Ty) {
394 printEscapedString(getCppName(Ty));
397 std::string CppWriter::getCppName(const Value* val) {
399 ValueMap::iterator I = ValueNames.find(val);
400 if (I != ValueNames.end() && I->first == val)
403 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
404 name = std::string("gvar_") +
405 getTypePrefix(GV->getType()->getElementType());
406 } else if (isa<Function>(val)) {
407 name = std::string("func_");
408 } else if (const Constant* C = dyn_cast<Constant>(val)) {
409 name = std::string("const_") + getTypePrefix(C->getType());
410 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
412 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
413 Function::const_arg_iterator(Arg)) + 1;
414 name = std::string("arg_") + utostr(argNum);
415 NameSet::iterator NI = UsedNames.find(name);
416 if (NI != UsedNames.end())
417 name += std::string("_") + utostr(uniqueNum++);
418 UsedNames.insert(name);
419 return ValueNames[val] = name;
421 name = getTypePrefix(val->getType());
424 name = getTypePrefix(val->getType());
427 name += val->getName();
429 name += utostr(uniqueNum++);
431 NameSet::iterator NI = UsedNames.find(name);
432 if (NI != UsedNames.end())
433 name += std::string("_") + utostr(uniqueNum++);
434 UsedNames.insert(name);
435 return ValueNames[val] = name;
438 void CppWriter::printCppName(const Value* val) {
439 printEscapedString(getCppName(val));
442 void CppWriter::printAttributes(const AttrListPtr &PAL,
443 const std::string &name) {
444 Out << "AttrListPtr " << name << "_PAL;";
446 if (!PAL.isEmpty()) {
447 Out << '{'; in(); nl(Out);
448 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
449 Out << "AttributeWithIndex PAWI;"; nl(Out);
450 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
451 unsigned index = PAL.getSlot(i).Index;
452 Attributes attrs = PAL.getSlot(i).Attrs;
453 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
454 #define HANDLE_ATTR(X) \
455 if (attrs & Attribute::X) \
456 Out << " | Attribute::" #X; \
457 attrs &= ~Attribute::X;
461 HANDLE_ATTR(NoReturn);
463 HANDLE_ATTR(StructRet);
464 HANDLE_ATTR(NoUnwind);
465 HANDLE_ATTR(NoAlias);
468 HANDLE_ATTR(ReadNone);
469 HANDLE_ATTR(ReadOnly);
470 HANDLE_ATTR(NoInline);
471 HANDLE_ATTR(AlwaysInline);
472 HANDLE_ATTR(OptimizeForSize);
473 HANDLE_ATTR(StackProtect);
474 HANDLE_ATTR(StackProtectReq);
475 HANDLE_ATTR(NoCapture);
476 HANDLE_ATTR(NoRedZone);
477 HANDLE_ATTR(NoImplicitFloat);
479 HANDLE_ATTR(InlineHint);
481 if (attrs & Attribute::StackAlignment)
482 Out << " | Attribute::constructStackAlignmentFromInt("
483 << Attribute::getStackAlignmentFromAttrs(attrs)
485 attrs &= ~Attribute::StackAlignment;
486 assert(attrs == 0 && "Unhandled attribute!");
489 Out << "Attrs.push_back(PAWI);";
492 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
499 void CppWriter::printType(const Type* Ty) {
500 // We don't print definitions for primitive types
501 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
504 // If we already defined this type, we don't need to define it again.
505 if (DefinedTypes.find(Ty) != DefinedTypes.end())
508 // Everything below needs the name for the type so get it now.
509 std::string typeName(getCppName(Ty));
511 // Print the type definition
512 switch (Ty->getTypeID()) {
513 case Type::FunctionTyID: {
514 const FunctionType* FT = cast<FunctionType>(Ty);
515 Out << "std::vector<Type*>" << typeName << "_args;";
517 FunctionType::param_iterator PI = FT->param_begin();
518 FunctionType::param_iterator PE = FT->param_end();
519 for (; PI != PE; ++PI) {
520 const Type* argTy = static_cast<const Type*>(*PI);
522 std::string argName(getCppName(argTy));
523 Out << typeName << "_args.push_back(" << argName;
527 printType(FT->getReturnType());
528 std::string retTypeName(getCppName(FT->getReturnType()));
529 Out << "FunctionType* " << typeName << " = FunctionType::get(";
530 in(); nl(Out) << "/*Result=*/" << retTypeName;
532 nl(Out) << "/*Params=*/" << typeName << "_args,";
533 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
538 case Type::StructTyID: {
539 const StructType* ST = cast<StructType>(Ty);
540 if (!ST->isAnonymous()) {
541 Out << "StructType *" << typeName << " = ";
542 Out << "StructType::createNamed(mod->getContext(), \"";
543 printEscapedString(ST->getName());
546 // Indicate that this type is now defined.
547 DefinedTypes.insert(Ty);
550 Out << "std::vector<Type*>" << typeName << "_fields;";
552 StructType::element_iterator EI = ST->element_begin();
553 StructType::element_iterator EE = ST->element_end();
554 for (; EI != EE; ++EI) {
555 const Type* fieldTy = static_cast<const Type*>(*EI);
557 std::string fieldName(getCppName(fieldTy));
558 Out << typeName << "_fields.push_back(" << fieldName;
563 if (ST->isAnonymous()) {
564 Out << "StructType *" << typeName << " = ";
565 Out << "StructType::get(" << "mod->getContext(), ";
567 Out << typeName << "->setBody(";
570 Out << typeName << "_fields, /*isPacked=*/"
571 << (ST->isPacked() ? "true" : "false") << ");";
575 case Type::ArrayTyID: {
576 const ArrayType* AT = cast<ArrayType>(Ty);
577 const Type* ET = AT->getElementType();
579 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
580 std::string elemName(getCppName(ET));
581 Out << "ArrayType* " << typeName << " = ArrayType::get("
583 << ", " << utostr(AT->getNumElements()) << ");";
588 case Type::PointerTyID: {
589 const PointerType* PT = cast<PointerType>(Ty);
590 const Type* ET = PT->getElementType();
592 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
593 std::string elemName(getCppName(ET));
594 Out << "PointerType* " << typeName << " = PointerType::get("
596 << ", " << utostr(PT->getAddressSpace()) << ");";
601 case Type::VectorTyID: {
602 const VectorType* PT = cast<VectorType>(Ty);
603 const Type* ET = PT->getElementType();
605 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
606 std::string elemName(getCppName(ET));
607 Out << "VectorType* " << typeName << " = VectorType::get("
609 << ", " << utostr(PT->getNumElements()) << ");";
615 error("Invalid TypeID");
618 // Indicate that this type is now defined.
619 DefinedTypes.insert(Ty);
621 // Finally, separate the type definition from other with a newline.
625 void CppWriter::printTypes(const Module* M) {
626 // Add all of the global variables to the value table.
627 for (Module::const_global_iterator I = TheModule->global_begin(),
628 E = TheModule->global_end(); I != E; ++I) {
629 if (I->hasInitializer())
630 printType(I->getInitializer()->getType());
631 printType(I->getType());
634 // Add all the functions to the table
635 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
637 printType(FI->getReturnType());
638 printType(FI->getFunctionType());
639 // Add all the function arguments
640 for (Function::const_arg_iterator AI = FI->arg_begin(),
641 AE = FI->arg_end(); AI != AE; ++AI) {
642 printType(AI->getType());
645 // Add all of the basic blocks and instructions
646 for (Function::const_iterator BB = FI->begin(),
647 E = FI->end(); BB != E; ++BB) {
648 printType(BB->getType());
649 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
651 printType(I->getType());
652 for (unsigned i = 0; i < I->getNumOperands(); ++i)
653 printType(I->getOperand(i)->getType());
660 // printConstant - Print out a constant pool entry...
661 void CppWriter::printConstant(const Constant *CV) {
662 // First, if the constant is actually a GlobalValue (variable or function)
663 // or its already in the constant list then we've printed it already and we
665 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
668 std::string constName(getCppName(CV));
669 std::string typeName(getCppName(CV->getType()));
671 if (isa<GlobalValue>(CV)) {
672 // Skip variables and functions, we emit them elsewhere
676 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
677 std::string constValue = CI->getValue().toString(10, true);
678 Out << "ConstantInt* " << constName
679 << " = ConstantInt::get(mod->getContext(), APInt("
680 << cast<IntegerType>(CI->getType())->getBitWidth()
681 << ", StringRef(\"" << constValue << "\"), 10));";
682 } else if (isa<ConstantAggregateZero>(CV)) {
683 Out << "ConstantAggregateZero* " << constName
684 << " = ConstantAggregateZero::get(" << typeName << ");";
685 } else if (isa<ConstantPointerNull>(CV)) {
686 Out << "ConstantPointerNull* " << constName
687 << " = ConstantPointerNull::get(" << typeName << ");";
688 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
689 Out << "ConstantFP* " << constName << " = ";
692 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
693 if (CA->isString() &&
694 CA->getType()->getElementType() ==
695 Type::getInt8Ty(CA->getContext())) {
696 Out << "Constant* " << constName <<
697 " = ConstantArray::get(mod->getContext(), \"";
698 std::string tmp = CA->getAsString();
699 bool nullTerminate = false;
700 if (tmp[tmp.length()-1] == 0) {
701 tmp.erase(tmp.length()-1);
702 nullTerminate = true;
704 printEscapedString(tmp);
705 // Determine if we want null termination or not.
707 Out << "\", true"; // Indicate that the null terminator should be
710 Out << "\", false";// No null terminator
713 Out << "std::vector<Constant*> " << constName << "_elems;";
715 unsigned N = CA->getNumOperands();
716 for (unsigned i = 0; i < N; ++i) {
717 printConstant(CA->getOperand(i)); // recurse to print operands
718 Out << constName << "_elems.push_back("
719 << getCppName(CA->getOperand(i)) << ");";
722 Out << "Constant* " << constName << " = ConstantArray::get("
723 << typeName << ", " << constName << "_elems);";
725 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
726 Out << "std::vector<Constant*> " << constName << "_fields;";
728 unsigned N = CS->getNumOperands();
729 for (unsigned i = 0; i < N; i++) {
730 printConstant(CS->getOperand(i));
731 Out << constName << "_fields.push_back("
732 << getCppName(CS->getOperand(i)) << ");";
735 Out << "Constant* " << constName << " = ConstantStruct::get("
736 << typeName << ", " << constName << "_fields);";
737 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
738 Out << "std::vector<Constant*> " << constName << "_elems;";
740 unsigned N = CP->getNumOperands();
741 for (unsigned i = 0; i < N; ++i) {
742 printConstant(CP->getOperand(i));
743 Out << constName << "_elems.push_back("
744 << getCppName(CP->getOperand(i)) << ");";
747 Out << "Constant* " << constName << " = ConstantVector::get("
748 << typeName << ", " << constName << "_elems);";
749 } else if (isa<UndefValue>(CV)) {
750 Out << "UndefValue* " << constName << " = UndefValue::get("
752 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
753 if (CE->getOpcode() == Instruction::GetElementPtr) {
754 Out << "std::vector<Constant*> " << constName << "_indices;";
756 printConstant(CE->getOperand(0));
757 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
758 printConstant(CE->getOperand(i));
759 Out << constName << "_indices.push_back("
760 << getCppName(CE->getOperand(i)) << ");";
763 Out << "Constant* " << constName
764 << " = ConstantExpr::getGetElementPtr("
765 << getCppName(CE->getOperand(0)) << ", "
766 << "&" << constName << "_indices[0], "
767 << constName << "_indices.size()"
769 } else if (CE->isCast()) {
770 printConstant(CE->getOperand(0));
771 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
772 switch (CE->getOpcode()) {
773 default: llvm_unreachable("Invalid cast opcode");
774 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
775 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
776 case Instruction::SExt: Out << "Instruction::SExt"; break;
777 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
778 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
779 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
780 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
781 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
782 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
783 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
784 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
785 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
787 Out << ", " << getCppName(CE->getOperand(0)) << ", "
788 << getCppName(CE->getType()) << ");";
790 unsigned N = CE->getNumOperands();
791 for (unsigned i = 0; i < N; ++i ) {
792 printConstant(CE->getOperand(i));
794 Out << "Constant* " << constName << " = ConstantExpr::";
795 switch (CE->getOpcode()) {
796 case Instruction::Add: Out << "getAdd("; break;
797 case Instruction::FAdd: Out << "getFAdd("; break;
798 case Instruction::Sub: Out << "getSub("; break;
799 case Instruction::FSub: Out << "getFSub("; break;
800 case Instruction::Mul: Out << "getMul("; break;
801 case Instruction::FMul: Out << "getFMul("; break;
802 case Instruction::UDiv: Out << "getUDiv("; break;
803 case Instruction::SDiv: Out << "getSDiv("; break;
804 case Instruction::FDiv: Out << "getFDiv("; break;
805 case Instruction::URem: Out << "getURem("; break;
806 case Instruction::SRem: Out << "getSRem("; break;
807 case Instruction::FRem: Out << "getFRem("; break;
808 case Instruction::And: Out << "getAnd("; break;
809 case Instruction::Or: Out << "getOr("; break;
810 case Instruction::Xor: Out << "getXor("; break;
811 case Instruction::ICmp:
812 Out << "getICmp(ICmpInst::ICMP_";
813 switch (CE->getPredicate()) {
814 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
815 case ICmpInst::ICMP_NE: Out << "NE"; break;
816 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
817 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
818 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
819 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
820 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
821 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
822 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
823 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
824 default: error("Invalid ICmp Predicate");
827 case Instruction::FCmp:
828 Out << "getFCmp(FCmpInst::FCMP_";
829 switch (CE->getPredicate()) {
830 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
831 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
832 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
833 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
834 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
835 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
836 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
837 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
838 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
839 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
840 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
841 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
842 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
843 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
844 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
845 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
846 default: error("Invalid FCmp Predicate");
849 case Instruction::Shl: Out << "getShl("; break;
850 case Instruction::LShr: Out << "getLShr("; break;
851 case Instruction::AShr: Out << "getAShr("; break;
852 case Instruction::Select: Out << "getSelect("; break;
853 case Instruction::ExtractElement: Out << "getExtractElement("; break;
854 case Instruction::InsertElement: Out << "getInsertElement("; break;
855 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
857 error("Invalid constant expression");
860 Out << getCppName(CE->getOperand(0));
861 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
862 Out << ", " << getCppName(CE->getOperand(i));
865 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
866 Out << "Constant* " << constName << " = ";
867 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
869 error("Bad Constant");
870 Out << "Constant* " << constName << " = 0; ";
875 void CppWriter::printConstants(const Module* M) {
876 // Traverse all the global variables looking for constant initializers
877 for (Module::const_global_iterator I = TheModule->global_begin(),
878 E = TheModule->global_end(); I != E; ++I)
879 if (I->hasInitializer())
880 printConstant(I->getInitializer());
882 // Traverse the LLVM functions looking for constants
883 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
885 // Add all of the basic blocks and instructions
886 for (Function::const_iterator BB = FI->begin(),
887 E = FI->end(); BB != E; ++BB) {
888 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
890 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
891 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
900 void CppWriter::printVariableUses(const GlobalVariable *GV) {
901 nl(Out) << "// Type Definitions";
903 printType(GV->getType());
904 if (GV->hasInitializer()) {
905 const Constant *Init = GV->getInitializer();
906 printType(Init->getType());
907 if (const Function *F = dyn_cast<Function>(Init)) {
908 nl(Out)<< "/ Function Declarations"; nl(Out);
909 printFunctionHead(F);
910 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
911 nl(Out) << "// Global Variable Declarations"; nl(Out);
912 printVariableHead(gv);
914 nl(Out) << "// Global Variable Definitions"; nl(Out);
915 printVariableBody(gv);
917 nl(Out) << "// Constant Definitions"; nl(Out);
923 void CppWriter::printVariableHead(const GlobalVariable *GV) {
924 nl(Out) << "GlobalVariable* " << getCppName(GV);
926 Out << " = mod->getGlobalVariable(mod->getContext(), ";
927 printEscapedString(GV->getName());
928 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
929 nl(Out) << "if (!" << getCppName(GV) << ") {";
930 in(); nl(Out) << getCppName(GV);
932 Out << " = new GlobalVariable(/*Module=*/*mod, ";
933 nl(Out) << "/*Type=*/";
934 printCppName(GV->getType()->getElementType());
936 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
938 nl(Out) << "/*Linkage=*/";
939 printLinkageType(GV->getLinkage());
941 nl(Out) << "/*Initializer=*/0, ";
942 if (GV->hasInitializer()) {
943 Out << "// has initializer, specified below";
945 nl(Out) << "/*Name=*/\"";
946 printEscapedString(GV->getName());
950 if (GV->hasSection()) {
952 Out << "->setSection(\"";
953 printEscapedString(GV->getSection());
957 if (GV->getAlignment()) {
959 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
962 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
964 Out << "->setVisibility(";
965 printVisibilityType(GV->getVisibility());
969 if (GV->isThreadLocal()) {
971 Out << "->setThreadLocal(true);";
975 out(); Out << "}"; nl(Out);
979 void CppWriter::printVariableBody(const GlobalVariable *GV) {
980 if (GV->hasInitializer()) {
982 Out << "->setInitializer(";
983 Out << getCppName(GV->getInitializer()) << ");";
988 std::string CppWriter::getOpName(Value* V) {
989 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
990 return getCppName(V);
992 // See if its alread in the map of forward references, if so just return the
993 // name we already set up for it
994 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
995 if (I != ForwardRefs.end())
998 // This is a new forward reference. Generate a unique name for it
999 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1001 // Yes, this is a hack. An Argument is the smallest instantiable value that
1002 // we can make as a placeholder for the real value. We'll replace these
1003 // Argument instances later.
1004 Out << "Argument* " << result << " = new Argument("
1005 << getCppName(V->getType()) << ");";
1007 ForwardRefs[V] = result;
1011 // printInstruction - This member is called for each Instruction in a function.
1012 void CppWriter::printInstruction(const Instruction *I,
1013 const std::string& bbname) {
1014 std::string iName(getCppName(I));
1016 // Before we emit this instruction, we need to take care of generating any
1017 // forward references. So, we get the names of all the operands in advance
1018 const unsigned Ops(I->getNumOperands());
1019 std::string* opNames = new std::string[Ops];
1020 for (unsigned i = 0; i < Ops; i++)
1021 opNames[i] = getOpName(I->getOperand(i));
1023 switch (I->getOpcode()) {
1025 error("Invalid instruction");
1028 case Instruction::Ret: {
1029 const ReturnInst* ret = cast<ReturnInst>(I);
1030 Out << "ReturnInst::Create(mod->getContext(), "
1031 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1034 case Instruction::Br: {
1035 const BranchInst* br = cast<BranchInst>(I);
1036 Out << "BranchInst::Create(" ;
1037 if (br->getNumOperands() == 3) {
1038 Out << opNames[2] << ", "
1039 << opNames[1] << ", "
1040 << opNames[0] << ", ";
1042 } else if (br->getNumOperands() == 1) {
1043 Out << opNames[0] << ", ";
1045 error("Branch with 2 operands?");
1047 Out << bbname << ");";
1050 case Instruction::Switch: {
1051 const SwitchInst *SI = cast<SwitchInst>(I);
1052 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1053 << opNames[0] << ", "
1054 << opNames[1] << ", "
1055 << SI->getNumCases() << ", " << bbname << ");";
1057 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
1058 Out << iName << "->addCase("
1059 << opNames[i] << ", "
1060 << opNames[i+1] << ");";
1065 case Instruction::IndirectBr: {
1066 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1067 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1068 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1070 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1071 Out << iName << "->addDestination(" << opNames[i] << ");";
1076 case Instruction::Invoke: {
1077 const InvokeInst* inv = cast<InvokeInst>(I);
1078 Out << "std::vector<Value*> " << iName << "_params;";
1080 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1081 Out << iName << "_params.push_back("
1082 << getOpName(inv->getArgOperand(i)) << ");";
1085 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1086 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1087 << getOpName(inv->getCalledFunction()) << ", "
1088 << getOpName(inv->getNormalDest()) << ", "
1089 << getOpName(inv->getUnwindDest()) << ", "
1090 << iName << "_params.begin(), "
1091 << iName << "_params.end(), \"";
1092 printEscapedString(inv->getName());
1093 Out << "\", " << bbname << ");";
1094 nl(Out) << iName << "->setCallingConv(";
1095 printCallingConv(inv->getCallingConv());
1097 printAttributes(inv->getAttributes(), iName);
1098 Out << iName << "->setAttributes(" << iName << "_PAL);";
1102 case Instruction::Unwind: {
1103 Out << "new UnwindInst("
1107 case Instruction::Unreachable: {
1108 Out << "new UnreachableInst("
1109 << "mod->getContext(), "
1113 case Instruction::Add:
1114 case Instruction::FAdd:
1115 case Instruction::Sub:
1116 case Instruction::FSub:
1117 case Instruction::Mul:
1118 case Instruction::FMul:
1119 case Instruction::UDiv:
1120 case Instruction::SDiv:
1121 case Instruction::FDiv:
1122 case Instruction::URem:
1123 case Instruction::SRem:
1124 case Instruction::FRem:
1125 case Instruction::And:
1126 case Instruction::Or:
1127 case Instruction::Xor:
1128 case Instruction::Shl:
1129 case Instruction::LShr:
1130 case Instruction::AShr:{
1131 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1132 switch (I->getOpcode()) {
1133 case Instruction::Add: Out << "Instruction::Add"; break;
1134 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1135 case Instruction::Sub: Out << "Instruction::Sub"; break;
1136 case Instruction::FSub: Out << "Instruction::FSub"; break;
1137 case Instruction::Mul: Out << "Instruction::Mul"; break;
1138 case Instruction::FMul: Out << "Instruction::FMul"; break;
1139 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1140 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1141 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1142 case Instruction::URem:Out << "Instruction::URem"; break;
1143 case Instruction::SRem:Out << "Instruction::SRem"; break;
1144 case Instruction::FRem:Out << "Instruction::FRem"; break;
1145 case Instruction::And: Out << "Instruction::And"; break;
1146 case Instruction::Or: Out << "Instruction::Or"; break;
1147 case Instruction::Xor: Out << "Instruction::Xor"; break;
1148 case Instruction::Shl: Out << "Instruction::Shl"; break;
1149 case Instruction::LShr:Out << "Instruction::LShr"; break;
1150 case Instruction::AShr:Out << "Instruction::AShr"; break;
1151 default: Out << "Instruction::BadOpCode"; break;
1153 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1154 printEscapedString(I->getName());
1155 Out << "\", " << bbname << ");";
1158 case Instruction::FCmp: {
1159 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1160 switch (cast<FCmpInst>(I)->getPredicate()) {
1161 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1162 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1163 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1164 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1165 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1166 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1167 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1168 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1169 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1170 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1171 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1172 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1173 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1174 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1175 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1176 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1177 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1179 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1180 printEscapedString(I->getName());
1184 case Instruction::ICmp: {
1185 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1186 switch (cast<ICmpInst>(I)->getPredicate()) {
1187 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1188 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1189 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1190 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1191 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1192 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1193 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1194 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1195 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1196 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1197 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1199 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1200 printEscapedString(I->getName());
1204 case Instruction::Alloca: {
1205 const AllocaInst* allocaI = cast<AllocaInst>(I);
1206 Out << "AllocaInst* " << iName << " = new AllocaInst("
1207 << getCppName(allocaI->getAllocatedType()) << ", ";
1208 if (allocaI->isArrayAllocation())
1209 Out << opNames[0] << ", ";
1211 printEscapedString(allocaI->getName());
1212 Out << "\", " << bbname << ");";
1213 if (allocaI->getAlignment())
1214 nl(Out) << iName << "->setAlignment("
1215 << allocaI->getAlignment() << ");";
1218 case Instruction::Load: {
1219 const LoadInst* load = cast<LoadInst>(I);
1220 Out << "LoadInst* " << iName << " = new LoadInst("
1221 << opNames[0] << ", \"";
1222 printEscapedString(load->getName());
1223 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1224 << ", " << bbname << ");";
1227 case Instruction::Store: {
1228 const StoreInst* store = cast<StoreInst>(I);
1229 Out << " new StoreInst("
1230 << opNames[0] << ", "
1231 << opNames[1] << ", "
1232 << (store->isVolatile() ? "true" : "false")
1233 << ", " << bbname << ");";
1236 case Instruction::GetElementPtr: {
1237 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1238 if (gep->getNumOperands() <= 2) {
1239 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1241 if (gep->getNumOperands() == 2)
1242 Out << ", " << opNames[1];
1244 Out << "std::vector<Value*> " << iName << "_indices;";
1246 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1247 Out << iName << "_indices.push_back("
1248 << opNames[i] << ");";
1251 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1252 << opNames[0] << ", " << iName << "_indices.begin(), "
1253 << iName << "_indices.end()";
1256 printEscapedString(gep->getName());
1257 Out << "\", " << bbname << ");";
1260 case Instruction::PHI: {
1261 const PHINode* phi = cast<PHINode>(I);
1263 Out << "PHINode* " << iName << " = PHINode::Create("
1264 << getCppName(phi->getType()) << ", "
1265 << phi->getNumIncomingValues() << ", \"";
1266 printEscapedString(phi->getName());
1267 Out << "\", " << bbname << ");";
1269 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
1270 Out << iName << "->addIncoming("
1271 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
1272 << getOpName(phi->getIncomingBlock(i)) << ");";
1277 case Instruction::Trunc:
1278 case Instruction::ZExt:
1279 case Instruction::SExt:
1280 case Instruction::FPTrunc:
1281 case Instruction::FPExt:
1282 case Instruction::FPToUI:
1283 case Instruction::FPToSI:
1284 case Instruction::UIToFP:
1285 case Instruction::SIToFP:
1286 case Instruction::PtrToInt:
1287 case Instruction::IntToPtr:
1288 case Instruction::BitCast: {
1289 const CastInst* cst = cast<CastInst>(I);
1290 Out << "CastInst* " << iName << " = new ";
1291 switch (I->getOpcode()) {
1292 case Instruction::Trunc: Out << "TruncInst"; break;
1293 case Instruction::ZExt: Out << "ZExtInst"; break;
1294 case Instruction::SExt: Out << "SExtInst"; break;
1295 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1296 case Instruction::FPExt: Out << "FPExtInst"; break;
1297 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1298 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1299 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1300 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1301 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1302 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1303 case Instruction::BitCast: Out << "BitCastInst"; break;
1304 default: assert(!"Unreachable"); break;
1306 Out << "(" << opNames[0] << ", "
1307 << getCppName(cst->getType()) << ", \"";
1308 printEscapedString(cst->getName());
1309 Out << "\", " << bbname << ");";
1312 case Instruction::Call: {
1313 const CallInst* call = cast<CallInst>(I);
1314 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1315 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1316 << getCppName(ila->getFunctionType()) << ", \""
1317 << ila->getAsmString() << "\", \""
1318 << ila->getConstraintString() << "\","
1319 << (ila->hasSideEffects() ? "true" : "false") << ");";
1322 if (call->getNumArgOperands() > 1) {
1323 Out << "std::vector<Value*> " << iName << "_params;";
1325 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
1326 Out << iName << "_params.push_back(" << opNames[i] << ");";
1329 Out << "CallInst* " << iName << " = CallInst::Create("
1330 << opNames[call->getNumArgOperands()] << ", "
1331 << iName << "_params.begin(), "
1332 << iName << "_params.end(), \"";
1333 } else if (call->getNumArgOperands() == 1) {
1334 Out << "CallInst* " << iName << " = CallInst::Create("
1335 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
1337 Out << "CallInst* " << iName << " = CallInst::Create("
1338 << opNames[call->getNumArgOperands()] << ", \"";
1340 printEscapedString(call->getName());
1341 Out << "\", " << bbname << ");";
1342 nl(Out) << iName << "->setCallingConv(";
1343 printCallingConv(call->getCallingConv());
1345 nl(Out) << iName << "->setTailCall("
1346 << (call->isTailCall() ? "true" : "false");
1349 printAttributes(call->getAttributes(), iName);
1350 Out << iName << "->setAttributes(" << iName << "_PAL);";
1354 case Instruction::Select: {
1355 const SelectInst* sel = cast<SelectInst>(I);
1356 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1357 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1358 printEscapedString(sel->getName());
1359 Out << "\", " << bbname << ");";
1362 case Instruction::UserOp1:
1364 case Instruction::UserOp2: {
1365 /// FIXME: What should be done here?
1368 case Instruction::VAArg: {
1369 const VAArgInst* va = cast<VAArgInst>(I);
1370 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1371 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1372 printEscapedString(va->getName());
1373 Out << "\", " << bbname << ");";
1376 case Instruction::ExtractElement: {
1377 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1378 Out << "ExtractElementInst* " << getCppName(eei)
1379 << " = new ExtractElementInst(" << opNames[0]
1380 << ", " << opNames[1] << ", \"";
1381 printEscapedString(eei->getName());
1382 Out << "\", " << bbname << ");";
1385 case Instruction::InsertElement: {
1386 const InsertElementInst* iei = cast<InsertElementInst>(I);
1387 Out << "InsertElementInst* " << getCppName(iei)
1388 << " = InsertElementInst::Create(" << opNames[0]
1389 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1390 printEscapedString(iei->getName());
1391 Out << "\", " << bbname << ");";
1394 case Instruction::ShuffleVector: {
1395 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1396 Out << "ShuffleVectorInst* " << getCppName(svi)
1397 << " = new ShuffleVectorInst(" << opNames[0]
1398 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1399 printEscapedString(svi->getName());
1400 Out << "\", " << bbname << ");";
1403 case Instruction::ExtractValue: {
1404 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1405 Out << "std::vector<unsigned> " << iName << "_indices;";
1407 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1408 Out << iName << "_indices.push_back("
1409 << evi->idx_begin()[i] << ");";
1412 Out << "ExtractValueInst* " << getCppName(evi)
1413 << " = ExtractValueInst::Create(" << opNames[0]
1415 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1416 printEscapedString(evi->getName());
1417 Out << "\", " << bbname << ");";
1420 case Instruction::InsertValue: {
1421 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1422 Out << "std::vector<unsigned> " << iName << "_indices;";
1424 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1425 Out << iName << "_indices.push_back("
1426 << ivi->idx_begin()[i] << ");";
1429 Out << "InsertValueInst* " << getCppName(ivi)
1430 << " = InsertValueInst::Create(" << opNames[0]
1431 << ", " << opNames[1] << ", "
1432 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1433 printEscapedString(ivi->getName());
1434 Out << "\", " << bbname << ");";
1438 DefinedValues.insert(I);
1443 // Print out the types, constants and declarations needed by one function
1444 void CppWriter::printFunctionUses(const Function* F) {
1445 nl(Out) << "// Type Definitions"; nl(Out);
1447 // Print the function's return type
1448 printType(F->getReturnType());
1450 // Print the function's function type
1451 printType(F->getFunctionType());
1453 // Print the types of each of the function's arguments
1454 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1456 printType(AI->getType());
1460 // Print type definitions for every type referenced by an instruction and
1461 // make a note of any global values or constants that are referenced
1462 SmallPtrSet<GlobalValue*,64> gvs;
1463 SmallPtrSet<Constant*,64> consts;
1464 for (Function::const_iterator BB = F->begin(), BE = F->end();
1466 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1468 // Print the type of the instruction itself
1469 printType(I->getType());
1471 // Print the type of each of the instruction's operands
1472 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1473 Value* operand = I->getOperand(i);
1474 printType(operand->getType());
1476 // If the operand references a GVal or Constant, make a note of it
1477 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1479 if (GenerationType != GenFunction)
1480 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1481 if (GVar->hasInitializer())
1482 consts.insert(GVar->getInitializer());
1483 } else if (Constant* C = dyn_cast<Constant>(operand)) {
1485 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1486 // If the operand references a GVal or Constant, make a note of it
1487 Value* operand = C->getOperand(j);
1488 printType(operand->getType());
1489 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1491 if (GenerationType != GenFunction)
1492 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1493 if (GVar->hasInitializer())
1494 consts.insert(GVar->getInitializer());
1502 // Print the function declarations for any functions encountered
1503 nl(Out) << "// Function Declarations"; nl(Out);
1504 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1506 if (Function* Fun = dyn_cast<Function>(*I)) {
1507 if (!is_inline || Fun != F)
1508 printFunctionHead(Fun);
1512 // Print the global variable declarations for any variables encountered
1513 nl(Out) << "// Global Variable Declarations"; nl(Out);
1514 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1516 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1517 printVariableHead(F);
1520 // Print the constants found
1521 nl(Out) << "// Constant Definitions"; nl(Out);
1522 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1523 E = consts.end(); I != E; ++I) {
1527 // Process the global variables definitions now that all the constants have
1528 // been emitted. These definitions just couple the gvars with their constant
1530 if (GenerationType != GenFunction) {
1531 nl(Out) << "// Global Variable Definitions"; nl(Out);
1532 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1534 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1535 printVariableBody(GV);
1540 void CppWriter::printFunctionHead(const Function* F) {
1541 nl(Out) << "Function* " << getCppName(F);
1543 Out << " = mod->getFunction(\"";
1544 printEscapedString(F->getName());
1545 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1546 nl(Out) << "if (!" << getCppName(F) << ") {";
1547 nl(Out) << getCppName(F);
1549 Out<< " = Function::Create(";
1550 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1551 nl(Out) << "/*Linkage=*/";
1552 printLinkageType(F->getLinkage());
1554 nl(Out) << "/*Name=*/\"";
1555 printEscapedString(F->getName());
1556 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1559 Out << "->setCallingConv(";
1560 printCallingConv(F->getCallingConv());
1563 if (F->hasSection()) {
1565 Out << "->setSection(\"" << F->getSection() << "\");";
1568 if (F->getAlignment()) {
1570 Out << "->setAlignment(" << F->getAlignment() << ");";
1573 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1575 Out << "->setVisibility(";
1576 printVisibilityType(F->getVisibility());
1582 Out << "->setGC(\"" << F->getGC() << "\");";
1589 printAttributes(F->getAttributes(), getCppName(F));
1591 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1595 void CppWriter::printFunctionBody(const Function *F) {
1596 if (F->isDeclaration())
1597 return; // external functions have no bodies.
1599 // Clear the DefinedValues and ForwardRefs maps because we can't have
1600 // cross-function forward refs
1601 ForwardRefs.clear();
1602 DefinedValues.clear();
1604 // Create all the argument values
1606 if (!F->arg_empty()) {
1607 Out << "Function::arg_iterator args = " << getCppName(F)
1608 << "->arg_begin();";
1611 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1613 Out << "Value* " << getCppName(AI) << " = args++;";
1615 if (AI->hasName()) {
1616 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1622 // Create all the basic blocks
1624 for (Function::const_iterator BI = F->begin(), BE = F->end();
1626 std::string bbname(getCppName(BI));
1627 Out << "BasicBlock* " << bbname <<
1628 " = BasicBlock::Create(mod->getContext(), \"";
1630 printEscapedString(BI->getName());
1631 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1635 // Output all of its basic blocks... for the function
1636 for (Function::const_iterator BI = F->begin(), BE = F->end();
1638 std::string bbname(getCppName(BI));
1639 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1642 // Output all of the instructions in the basic block...
1643 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1645 printInstruction(I,bbname);
1649 // Loop over the ForwardRefs and resolve them now that all instructions
1651 if (!ForwardRefs.empty()) {
1652 nl(Out) << "// Resolve Forward References";
1656 while (!ForwardRefs.empty()) {
1657 ForwardRefMap::iterator I = ForwardRefs.begin();
1658 Out << I->second << "->replaceAllUsesWith("
1659 << getCppName(I->first) << "); delete " << I->second << ";";
1661 ForwardRefs.erase(I);
1665 void CppWriter::printInline(const std::string& fname,
1666 const std::string& func) {
1667 const Function* F = TheModule->getFunction(func);
1669 error(std::string("Function '") + func + "' not found in input module");
1672 if (F->isDeclaration()) {
1673 error(std::string("Function '") + func + "' is external!");
1676 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1678 unsigned arg_count = 1;
1679 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1681 Out << ", Value* arg_" << arg_count;
1686 printFunctionUses(F);
1687 printFunctionBody(F);
1689 Out << "return " << getCppName(F->begin()) << ";";
1694 void CppWriter::printModuleBody() {
1695 // Print out all the type definitions
1696 nl(Out) << "// Type Definitions"; nl(Out);
1697 printTypes(TheModule);
1699 // Functions can call each other and global variables can reference them so
1700 // define all the functions first before emitting their function bodies.
1701 nl(Out) << "// Function Declarations"; nl(Out);
1702 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1704 printFunctionHead(I);
1706 // Process the global variables declarations. We can't initialze them until
1707 // after the constants are printed so just print a header for each global
1708 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1709 for (Module::const_global_iterator I = TheModule->global_begin(),
1710 E = TheModule->global_end(); I != E; ++I) {
1711 printVariableHead(I);
1714 // Print out all the constants definitions. Constants don't recurse except
1715 // through GlobalValues. All GlobalValues have been declared at this point
1716 // so we can proceed to generate the constants.
1717 nl(Out) << "// Constant Definitions"; nl(Out);
1718 printConstants(TheModule);
1720 // Process the global variables definitions now that all the constants have
1721 // been emitted. These definitions just couple the gvars with their constant
1723 nl(Out) << "// Global Variable Definitions"; nl(Out);
1724 for (Module::const_global_iterator I = TheModule->global_begin(),
1725 E = TheModule->global_end(); I != E; ++I) {
1726 printVariableBody(I);
1729 // Finally, we can safely put out all of the function bodies.
1730 nl(Out) << "// Function Definitions"; nl(Out);
1731 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1733 if (!I->isDeclaration()) {
1734 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1738 printFunctionBody(I);
1745 void CppWriter::printProgram(const std::string& fname,
1746 const std::string& mName) {
1747 Out << "#include <llvm/LLVMContext.h>\n";
1748 Out << "#include <llvm/Module.h>\n";
1749 Out << "#include <llvm/DerivedTypes.h>\n";
1750 Out << "#include <llvm/Constants.h>\n";
1751 Out << "#include <llvm/GlobalVariable.h>\n";
1752 Out << "#include <llvm/Function.h>\n";
1753 Out << "#include <llvm/CallingConv.h>\n";
1754 Out << "#include <llvm/BasicBlock.h>\n";
1755 Out << "#include <llvm/Instructions.h>\n";
1756 Out << "#include <llvm/InlineAsm.h>\n";
1757 Out << "#include <llvm/Support/FormattedStream.h>\n";
1758 Out << "#include <llvm/Support/MathExtras.h>\n";
1759 Out << "#include <llvm/Pass.h>\n";
1760 Out << "#include <llvm/PassManager.h>\n";
1761 Out << "#include <llvm/ADT/SmallVector.h>\n";
1762 Out << "#include <llvm/Analysis/Verifier.h>\n";
1763 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1764 Out << "#include <algorithm>\n";
1765 Out << "using namespace llvm;\n\n";
1766 Out << "Module* " << fname << "();\n\n";
1767 Out << "int main(int argc, char**argv) {\n";
1768 Out << " Module* Mod = " << fname << "();\n";
1769 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1770 Out << " PassManager PM;\n";
1771 Out << " PM.add(createPrintModulePass(&outs()));\n";
1772 Out << " PM.run(*Mod);\n";
1773 Out << " return 0;\n";
1775 printModule(fname,mName);
1778 void CppWriter::printModule(const std::string& fname,
1779 const std::string& mName) {
1780 nl(Out) << "Module* " << fname << "() {";
1781 nl(Out,1) << "// Module Construction";
1782 nl(Out) << "Module* mod = new Module(\"";
1783 printEscapedString(mName);
1784 Out << "\", getGlobalContext());";
1785 if (!TheModule->getTargetTriple().empty()) {
1786 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1788 if (!TheModule->getTargetTriple().empty()) {
1789 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1793 if (!TheModule->getModuleInlineAsm().empty()) {
1794 nl(Out) << "mod->setModuleInlineAsm(\"";
1795 printEscapedString(TheModule->getModuleInlineAsm());
1800 // Loop over the dependent libraries and emit them.
1801 Module::lib_iterator LI = TheModule->lib_begin();
1802 Module::lib_iterator LE = TheModule->lib_end();
1804 Out << "mod->addLibrary(\"" << *LI << "\");";
1809 nl(Out) << "return mod;";
1814 void CppWriter::printContents(const std::string& fname,
1815 const std::string& mName) {
1816 Out << "\nModule* " << fname << "(Module *mod) {\n";
1817 Out << "\nmod->setModuleIdentifier(\"";
1818 printEscapedString(mName);
1821 Out << "\nreturn mod;\n";
1825 void CppWriter::printFunction(const std::string& fname,
1826 const std::string& funcName) {
1827 const Function* F = TheModule->getFunction(funcName);
1829 error(std::string("Function '") + funcName + "' not found in input module");
1832 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1833 printFunctionUses(F);
1834 printFunctionHead(F);
1835 printFunctionBody(F);
1836 Out << "return " << getCppName(F) << ";\n";
1840 void CppWriter::printFunctions() {
1841 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1842 Module::const_iterator I = funcs.begin();
1843 Module::const_iterator IE = funcs.end();
1845 for (; I != IE; ++I) {
1846 const Function &func = *I;
1847 if (!func.isDeclaration()) {
1848 std::string name("define_");
1849 name += func.getName();
1850 printFunction(name, func.getName());
1855 void CppWriter::printVariable(const std::string& fname,
1856 const std::string& varName) {
1857 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1860 error(std::string("Variable '") + varName + "' not found in input module");
1863 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1864 printVariableUses(GV);
1865 printVariableHead(GV);
1866 printVariableBody(GV);
1867 Out << "return " << getCppName(GV) << ";\n";
1871 void CppWriter::printType(const std::string &fname,
1872 const std::string &typeName) {
1873 const Type* Ty = TheModule->getTypeByName(typeName);
1875 error(std::string("Type '") + typeName + "' not found in input module");
1878 Out << "\nType* " << fname << "(Module *mod) {\n";
1880 Out << "return " << getCppName(Ty) << ";\n";
1884 bool CppWriter::runOnModule(Module &M) {
1888 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1890 // Get the name of the function we're supposed to generate
1891 std::string fname = FuncName.getValue();
1893 // Get the name of the thing we are to generate
1894 std::string tgtname = NameToGenerate.getValue();
1895 if (GenerationType == GenModule ||
1896 GenerationType == GenContents ||
1897 GenerationType == GenProgram ||
1898 GenerationType == GenFunctions) {
1899 if (tgtname == "!bad!") {
1900 if (M.getModuleIdentifier() == "-")
1901 tgtname = "<stdin>";
1903 tgtname = M.getModuleIdentifier();
1905 } else if (tgtname == "!bad!")
1906 error("You must use the -for option with -gen-{function,variable,type}");
1908 switch (WhatToGenerate(GenerationType)) {
1911 fname = "makeLLVMModule";
1912 printProgram(fname,tgtname);
1916 fname = "makeLLVMModule";
1917 printModule(fname,tgtname);
1921 fname = "makeLLVMModuleContents";
1922 printContents(fname,tgtname);
1926 fname = "makeLLVMFunction";
1927 printFunction(fname,tgtname);
1934 fname = "makeLLVMInline";
1935 printInline(fname,tgtname);
1939 fname = "makeLLVMVariable";
1940 printVariable(fname,tgtname);
1944 fname = "makeLLVMType";
1945 printType(fname,tgtname);
1948 error("Invalid generation option");
1954 char CppWriter::ID = 0;
1956 //===----------------------------------------------------------------------===//
1957 // External Interface declaration
1958 //===----------------------------------------------------------------------===//
1960 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
1961 formatted_raw_ostream &o,
1962 CodeGenFileType FileType,
1963 CodeGenOpt::Level OptLevel,
1964 bool DisableVerify) {
1965 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
1966 PM.add(new CppWriter(o));