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/MCAsmInfo.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Config/config.h"
41 static cl::opt<std::string>
42 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
43 cl::value_desc("function name"));
56 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
57 cl::desc("Choose what kind of output to generate"),
60 clEnumValN(GenProgram, "program", "Generate a complete program"),
61 clEnumValN(GenModule, "module", "Generate a module definition"),
62 clEnumValN(GenContents, "contents", "Generate contents of a module"),
63 clEnumValN(GenFunction, "function", "Generate a function definition"),
64 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
65 clEnumValN(GenInline, "inline", "Generate an inline function"),
66 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
67 clEnumValN(GenType, "type", "Generate a type definition"),
72 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
73 cl::desc("Specify the name of the thing to generate"),
76 extern "C" void LLVMInitializeCppBackendTarget() {
77 // Register the target.
78 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
82 typedef std::vector<Type*> TypeList;
83 typedef std::map<Type*,std::string> TypeMap;
84 typedef std::map<const Value*,std::string> ValueMap;
85 typedef std::set<std::string> NameSet;
86 typedef std::set<Type*> TypeSet;
87 typedef std::set<const Value*> ValueSet;
88 typedef std::map<const Value*,std::string> ForwardRefMap;
90 /// CppWriter - This class is the main chunk of code that converts an LLVM
91 /// module to a C++ translation unit.
92 class CppWriter : public ModulePass {
93 formatted_raw_ostream &Out;
94 const Module *TheModule;
100 ValueSet DefinedValues;
101 ForwardRefMap ForwardRefs;
103 unsigned indent_level;
107 explicit CppWriter(formatted_raw_ostream &o) :
108 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
110 virtual const char *getPassName() const { return "C++ backend"; }
112 bool runOnModule(Module &M);
114 void printProgram(const std::string& fname, const std::string& modName );
115 void printModule(const std::string& fname, const std::string& modName );
116 void printContents(const std::string& fname, const std::string& modName );
117 void printFunction(const std::string& fname, const std::string& funcName );
118 void printFunctions();
119 void printInline(const std::string& fname, const std::string& funcName );
120 void printVariable(const std::string& fname, const std::string& varName );
121 void printType(const std::string& fname, const std::string& typeName );
123 void error(const std::string& msg);
126 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
127 inline void in() { indent_level++; }
128 inline void out() { if (indent_level >0) indent_level--; }
131 void printLinkageType(GlobalValue::LinkageTypes LT);
132 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
133 void printCallingConv(CallingConv::ID cc);
134 void printEscapedString(const std::string& str);
135 void printCFP(const ConstantFP* CFP);
137 std::string getCppName(Type* val);
138 inline void printCppName(Type* val);
140 std::string getCppName(const Value* val);
141 inline void printCppName(const Value* val);
143 void printAttributes(const AttrListPtr &PAL, const std::string &name);
144 void printType(Type* Ty);
145 void printTypes(const Module* M);
147 void printConstant(const Constant *CPV);
148 void printConstants(const Module* M);
150 void printVariableUses(const GlobalVariable *GV);
151 void printVariableHead(const GlobalVariable *GV);
152 void printVariableBody(const GlobalVariable *GV);
154 void printFunctionUses(const Function *F);
155 void printFunctionHead(const Function *F);
156 void printFunctionBody(const Function *F);
157 void printInstruction(const Instruction *I, const std::string& bbname);
158 std::string getOpName(const Value*);
160 void printModuleBody();
162 } // end anonymous namespace.
164 formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
166 if (delta >= 0 || indent_level >= unsigned(-delta))
167 indent_level += delta;
168 Out.indent(indent_level);
172 static inline void sanitize(std::string &str) {
173 for (size_t i = 0; i < str.length(); ++i)
174 if (!isalnum(str[i]) && str[i] != '_')
178 static std::string getTypePrefix(Type *Ty) {
179 switch (Ty->getTypeID()) {
180 case Type::VoidTyID: return "void_";
181 case Type::IntegerTyID:
182 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
183 case Type::FloatTyID: return "float_";
184 case Type::DoubleTyID: return "double_";
185 case Type::LabelTyID: return "label_";
186 case Type::FunctionTyID: return "func_";
187 case Type::StructTyID: return "struct_";
188 case Type::ArrayTyID: return "array_";
189 case Type::PointerTyID: return "ptr_";
190 case Type::VectorTyID: return "packed_";
191 default: return "other_";
195 void CppWriter::error(const std::string& msg) {
196 report_fatal_error(msg);
199 static inline std::string ftostr(const APFloat& V) {
201 if (&V.getSemantics() == &APFloat::IEEEdouble) {
202 raw_string_ostream(Buf) << V.convertToDouble();
204 } else if (&V.getSemantics() == &APFloat::IEEEsingle) {
205 raw_string_ostream(Buf) << (double)V.convertToFloat();
208 return "<unknown format in ftostr>"; // error
211 // printCFP - Print a floating point constant .. very carefully :)
212 // This makes sure that conversion to/from floating yields the same binary
213 // result so that we don't lose precision.
214 void CppWriter::printCFP(const ConstantFP *CFP) {
216 APFloat APF = APFloat(CFP->getValueAPF()); // copy
217 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
218 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
219 Out << "ConstantFP::get(mod->getContext(), ";
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::getDoubleTy(CFP->getContext()))
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::getDoubleTy(CFP->getContext()))
249 Out << StrVal << "f";
250 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
251 Out << "BitsToDouble(0x"
252 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
253 << "ULL) /* " << StrVal << " */";
255 Out << "BitsToFloat(0x"
256 << utohexstr((uint32_t)CFP->getValueAPF().
257 bitcastToAPInt().getZExtValue())
258 << "U) /* " << StrVal << " */";
266 void CppWriter::printCallingConv(CallingConv::ID cc){
267 // Print the calling convention.
269 case CallingConv::C: Out << "CallingConv::C"; break;
270 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
271 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
272 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
273 default: Out << cc; break;
277 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
279 case GlobalValue::InternalLinkage:
280 Out << "GlobalValue::InternalLinkage"; break;
281 case GlobalValue::PrivateLinkage:
282 Out << "GlobalValue::PrivateLinkage"; break;
283 case GlobalValue::LinkerPrivateLinkage:
284 Out << "GlobalValue::LinkerPrivateLinkage"; break;
285 case GlobalValue::LinkerPrivateWeakLinkage:
286 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
287 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
288 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
289 case GlobalValue::AvailableExternallyLinkage:
290 Out << "GlobalValue::AvailableExternallyLinkage "; break;
291 case GlobalValue::LinkOnceAnyLinkage:
292 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
293 case GlobalValue::LinkOnceODRLinkage:
294 Out << "GlobalValue::LinkOnceODRLinkage "; break;
295 case GlobalValue::WeakAnyLinkage:
296 Out << "GlobalValue::WeakAnyLinkage"; break;
297 case GlobalValue::WeakODRLinkage:
298 Out << "GlobalValue::WeakODRLinkage"; break;
299 case GlobalValue::AppendingLinkage:
300 Out << "GlobalValue::AppendingLinkage"; break;
301 case GlobalValue::ExternalLinkage:
302 Out << "GlobalValue::ExternalLinkage"; break;
303 case GlobalValue::DLLImportLinkage:
304 Out << "GlobalValue::DLLImportLinkage"; break;
305 case GlobalValue::DLLExportLinkage:
306 Out << "GlobalValue::DLLExportLinkage"; break;
307 case GlobalValue::ExternalWeakLinkage:
308 Out << "GlobalValue::ExternalWeakLinkage"; break;
309 case GlobalValue::CommonLinkage:
310 Out << "GlobalValue::CommonLinkage"; break;
314 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
316 case GlobalValue::DefaultVisibility:
317 Out << "GlobalValue::DefaultVisibility";
319 case GlobalValue::HiddenVisibility:
320 Out << "GlobalValue::HiddenVisibility";
322 case GlobalValue::ProtectedVisibility:
323 Out << "GlobalValue::ProtectedVisibility";
328 // printEscapedString - Print each character of the specified string, escaping
329 // it if it is not printable or if it is an escape char.
330 void CppWriter::printEscapedString(const std::string &Str) {
331 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
332 unsigned char C = Str[i];
333 if (isprint(C) && C != '"' && C != '\\') {
337 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
338 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
343 std::string CppWriter::getCppName(Type* Ty) {
344 // First, handle the primitive types .. easy
345 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
346 switch (Ty->getTypeID()) {
347 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
348 case Type::IntegerTyID: {
349 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
350 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
352 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
353 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
354 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
355 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
356 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
358 error("Invalid primitive type");
361 // shouldn't be returned, but make it sensible
362 return "Type::getVoidTy(mod->getContext())";
365 // Now, see if we've seen the type before and return that
366 TypeMap::iterator I = TypeNames.find(Ty);
367 if (I != TypeNames.end())
370 // Okay, let's build a new name for this type. Start with a prefix
371 const char* prefix = 0;
372 switch (Ty->getTypeID()) {
373 case Type::FunctionTyID: prefix = "FuncTy_"; break;
374 case Type::StructTyID: prefix = "StructTy_"; break;
375 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
376 case Type::PointerTyID: prefix = "PointerTy_"; break;
377 case Type::VectorTyID: prefix = "VectorTy_"; break;
378 default: prefix = "OtherTy_"; break; // prevent breakage
381 // See if the type has a name in the symboltable and build accordingly
383 if (StructType *STy = dyn_cast<StructType>(Ty))
385 name = STy->getName();
388 name = utostr(uniqueNum++);
390 name = std::string(prefix) + name;
394 return TypeNames[Ty] = name;
397 void CppWriter::printCppName(Type* Ty) {
398 printEscapedString(getCppName(Ty));
401 std::string CppWriter::getCppName(const Value* val) {
403 ValueMap::iterator I = ValueNames.find(val);
404 if (I != ValueNames.end() && I->first == val)
407 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
408 name = std::string("gvar_") +
409 getTypePrefix(GV->getType()->getElementType());
410 } else if (isa<Function>(val)) {
411 name = std::string("func_");
412 } else if (const Constant* C = dyn_cast<Constant>(val)) {
413 name = std::string("const_") + getTypePrefix(C->getType());
414 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
416 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
417 Function::const_arg_iterator(Arg)) + 1;
418 name = std::string("arg_") + utostr(argNum);
419 NameSet::iterator NI = UsedNames.find(name);
420 if (NI != UsedNames.end())
421 name += std::string("_") + utostr(uniqueNum++);
422 UsedNames.insert(name);
423 return ValueNames[val] = name;
425 name = getTypePrefix(val->getType());
428 name = getTypePrefix(val->getType());
431 name += val->getName();
433 name += utostr(uniqueNum++);
435 NameSet::iterator NI = UsedNames.find(name);
436 if (NI != UsedNames.end())
437 name += std::string("_") + utostr(uniqueNum++);
438 UsedNames.insert(name);
439 return ValueNames[val] = name;
442 void CppWriter::printCppName(const Value* val) {
443 printEscapedString(getCppName(val));
446 void CppWriter::printAttributes(const AttrListPtr &PAL,
447 const std::string &name) {
448 Out << "AttrListPtr " << name << "_PAL;";
450 if (!PAL.isEmpty()) {
451 Out << '{'; in(); nl(Out);
452 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
453 Out << "AttributeWithIndex PAWI;"; nl(Out);
454 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
455 unsigned index = PAL.getSlot(i).Index;
456 Attributes attrs = PAL.getSlot(i).Attrs;
457 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = Attribute::None ";
458 #define HANDLE_ATTR(X) \
459 if (attrs & Attribute::X) \
460 Out << " | Attribute::" #X; \
461 attrs &= ~Attribute::X;
465 HANDLE_ATTR(NoReturn);
467 HANDLE_ATTR(StructRet);
468 HANDLE_ATTR(NoUnwind);
469 HANDLE_ATTR(NoAlias);
472 HANDLE_ATTR(ReadNone);
473 HANDLE_ATTR(ReadOnly);
474 HANDLE_ATTR(NoInline);
475 HANDLE_ATTR(AlwaysInline);
476 HANDLE_ATTR(OptimizeForSize);
477 HANDLE_ATTR(StackProtect);
478 HANDLE_ATTR(StackProtectReq);
479 HANDLE_ATTR(NoCapture);
480 HANDLE_ATTR(NoRedZone);
481 HANDLE_ATTR(NoImplicitFloat);
483 HANDLE_ATTR(InlineHint);
484 HANDLE_ATTR(ReturnsTwice);
485 HANDLE_ATTR(UWTable);
486 HANDLE_ATTR(NonLazyBind);
488 if (attrs & Attribute::StackAlignment)
489 Out << " | Attribute::constructStackAlignmentFromInt("
490 << Attribute::getStackAlignmentFromAttrs(attrs)
492 attrs &= ~Attribute::StackAlignment;
493 assert(attrs == 0 && "Unhandled attribute!");
496 Out << "Attrs.push_back(PAWI);";
499 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
506 void CppWriter::printType(Type* Ty) {
507 // We don't print definitions for primitive types
508 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
511 // If we already defined this type, we don't need to define it again.
512 if (DefinedTypes.find(Ty) != DefinedTypes.end())
515 // Everything below needs the name for the type so get it now.
516 std::string typeName(getCppName(Ty));
518 // Print the type definition
519 switch (Ty->getTypeID()) {
520 case Type::FunctionTyID: {
521 FunctionType* FT = cast<FunctionType>(Ty);
522 Out << "std::vector<Type*>" << typeName << "_args;";
524 FunctionType::param_iterator PI = FT->param_begin();
525 FunctionType::param_iterator PE = FT->param_end();
526 for (; PI != PE; ++PI) {
527 Type* argTy = static_cast<Type*>(*PI);
529 std::string argName(getCppName(argTy));
530 Out << typeName << "_args.push_back(" << argName;
534 printType(FT->getReturnType());
535 std::string retTypeName(getCppName(FT->getReturnType()));
536 Out << "FunctionType* " << typeName << " = FunctionType::get(";
537 in(); nl(Out) << "/*Result=*/" << retTypeName;
539 nl(Out) << "/*Params=*/" << typeName << "_args,";
540 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
545 case Type::StructTyID: {
546 StructType* ST = cast<StructType>(Ty);
547 if (!ST->isLiteral()) {
548 Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
549 printEscapedString(ST->getName());
552 Out << "if (!" << typeName << ") {";
554 Out << typeName << " = ";
555 Out << "StructType::create(mod->getContext(), \"";
556 printEscapedString(ST->getName());
561 // Indicate that this type is now defined.
562 DefinedTypes.insert(Ty);
565 Out << "std::vector<Type*>" << typeName << "_fields;";
567 StructType::element_iterator EI = ST->element_begin();
568 StructType::element_iterator EE = ST->element_end();
569 for (; EI != EE; ++EI) {
570 Type* fieldTy = static_cast<Type*>(*EI);
572 std::string fieldName(getCppName(fieldTy));
573 Out << typeName << "_fields.push_back(" << fieldName;
578 if (ST->isLiteral()) {
579 Out << "StructType *" << typeName << " = ";
580 Out << "StructType::get(" << "mod->getContext(), ";
582 Out << "if (" << typeName << "->isOpaque()) {";
584 Out << typeName << "->setBody(";
587 Out << typeName << "_fields, /*isPacked=*/"
588 << (ST->isPacked() ? "true" : "false") << ");";
590 if (!ST->isLiteral()) {
596 case Type::ArrayTyID: {
597 ArrayType* AT = cast<ArrayType>(Ty);
598 Type* ET = AT->getElementType();
600 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
601 std::string elemName(getCppName(ET));
602 Out << "ArrayType* " << typeName << " = ArrayType::get("
604 << ", " << utostr(AT->getNumElements()) << ");";
609 case Type::PointerTyID: {
610 PointerType* PT = cast<PointerType>(Ty);
611 Type* ET = PT->getElementType();
613 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
614 std::string elemName(getCppName(ET));
615 Out << "PointerType* " << typeName << " = PointerType::get("
617 << ", " << utostr(PT->getAddressSpace()) << ");";
622 case Type::VectorTyID: {
623 VectorType* PT = cast<VectorType>(Ty);
624 Type* ET = PT->getElementType();
626 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
627 std::string elemName(getCppName(ET));
628 Out << "VectorType* " << typeName << " = VectorType::get("
630 << ", " << utostr(PT->getNumElements()) << ");";
636 error("Invalid TypeID");
639 // Indicate that this type is now defined.
640 DefinedTypes.insert(Ty);
642 // Finally, separate the type definition from other with a newline.
646 void CppWriter::printTypes(const Module* M) {
647 // Add all of the global variables to the value table.
648 for (Module::const_global_iterator I = TheModule->global_begin(),
649 E = TheModule->global_end(); I != E; ++I) {
650 if (I->hasInitializer())
651 printType(I->getInitializer()->getType());
652 printType(I->getType());
655 // Add all the functions to the table
656 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
658 printType(FI->getReturnType());
659 printType(FI->getFunctionType());
660 // Add all the function arguments
661 for (Function::const_arg_iterator AI = FI->arg_begin(),
662 AE = FI->arg_end(); AI != AE; ++AI) {
663 printType(AI->getType());
666 // Add all of the basic blocks and instructions
667 for (Function::const_iterator BB = FI->begin(),
668 E = FI->end(); BB != E; ++BB) {
669 printType(BB->getType());
670 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
672 printType(I->getType());
673 for (unsigned i = 0; i < I->getNumOperands(); ++i)
674 printType(I->getOperand(i)->getType());
681 // printConstant - Print out a constant pool entry...
682 void CppWriter::printConstant(const Constant *CV) {
683 // First, if the constant is actually a GlobalValue (variable or function)
684 // or its already in the constant list then we've printed it already and we
686 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
689 std::string constName(getCppName(CV));
690 std::string typeName(getCppName(CV->getType()));
692 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
693 std::string constValue = CI->getValue().toString(10, true);
694 Out << "ConstantInt* " << constName
695 << " = ConstantInt::get(mod->getContext(), APInt("
696 << cast<IntegerType>(CI->getType())->getBitWidth()
697 << ", StringRef(\"" << constValue << "\"), 10));";
698 } else if (isa<ConstantAggregateZero>(CV)) {
699 Out << "ConstantAggregateZero* " << constName
700 << " = ConstantAggregateZero::get(" << typeName << ");";
701 } else if (isa<ConstantPointerNull>(CV)) {
702 Out << "ConstantPointerNull* " << constName
703 << " = ConstantPointerNull::get(" << typeName << ");";
704 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
705 Out << "ConstantFP* " << constName << " = ";
708 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
709 Out << "std::vector<Constant*> " << constName << "_elems;";
711 unsigned N = CA->getNumOperands();
712 for (unsigned i = 0; i < N; ++i) {
713 printConstant(CA->getOperand(i)); // recurse to print operands
714 Out << constName << "_elems.push_back("
715 << getCppName(CA->getOperand(i)) << ");";
718 Out << "Constant* " << constName << " = ConstantArray::get("
719 << typeName << ", " << constName << "_elems);";
720 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
721 Out << "std::vector<Constant*> " << constName << "_fields;";
723 unsigned N = CS->getNumOperands();
724 for (unsigned i = 0; i < N; i++) {
725 printConstant(CS->getOperand(i));
726 Out << constName << "_fields.push_back("
727 << getCppName(CS->getOperand(i)) << ");";
730 Out << "Constant* " << constName << " = ConstantStruct::get("
731 << typeName << ", " << constName << "_fields);";
732 } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
733 Out << "std::vector<Constant*> " << constName << "_elems;";
735 unsigned N = CVec->getNumOperands();
736 for (unsigned i = 0; i < N; ++i) {
737 printConstant(CVec->getOperand(i));
738 Out << constName << "_elems.push_back("
739 << getCppName(CVec->getOperand(i)) << ");";
742 Out << "Constant* " << constName << " = ConstantVector::get("
743 << typeName << ", " << constName << "_elems);";
744 } else if (isa<UndefValue>(CV)) {
745 Out << "UndefValue* " << constName << " = UndefValue::get("
747 } else if (const ConstantDataSequential *CDS =
748 dyn_cast<ConstantDataSequential>(CV)) {
749 if (CDS->isString()) {
750 Out << "Constant *" << constName <<
751 " = ConstantDataArray::getString(mod->getContext(), \"";
752 StringRef Str = CDS->getAsString();
753 bool nullTerminate = false;
754 if (Str.back() == 0) {
755 Str = Str.drop_back();
756 nullTerminate = true;
758 printEscapedString(Str);
759 // Determine if we want null termination or not.
763 Out << "\", false);";// No null terminator
765 // TODO: Could generate more efficient code generating CDS calls instead.
766 Out << "std::vector<Constant*> " << constName << "_elems;";
768 for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
769 Constant *Elt = CDS->getElementAsConstant(i);
771 Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
774 Out << "Constant* " << constName;
776 if (isa<ArrayType>(CDS->getType()))
777 Out << " = ConstantArray::get(";
779 Out << " = ConstantVector::get(";
780 Out << typeName << ", " << constName << "_elems);";
782 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
783 if (CE->getOpcode() == Instruction::GetElementPtr) {
784 Out << "std::vector<Constant*> " << constName << "_indices;";
786 printConstant(CE->getOperand(0));
787 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
788 printConstant(CE->getOperand(i));
789 Out << constName << "_indices.push_back("
790 << getCppName(CE->getOperand(i)) << ");";
793 Out << "Constant* " << constName
794 << " = ConstantExpr::getGetElementPtr("
795 << getCppName(CE->getOperand(0)) << ", "
796 << constName << "_indices);";
797 } else if (CE->isCast()) {
798 printConstant(CE->getOperand(0));
799 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
800 switch (CE->getOpcode()) {
801 default: llvm_unreachable("Invalid cast opcode");
802 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
803 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
804 case Instruction::SExt: Out << "Instruction::SExt"; break;
805 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
806 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
807 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
808 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
809 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
810 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
811 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
812 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
813 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
815 Out << ", " << getCppName(CE->getOperand(0)) << ", "
816 << getCppName(CE->getType()) << ");";
818 unsigned N = CE->getNumOperands();
819 for (unsigned i = 0; i < N; ++i ) {
820 printConstant(CE->getOperand(i));
822 Out << "Constant* " << constName << " = ConstantExpr::";
823 switch (CE->getOpcode()) {
824 case Instruction::Add: Out << "getAdd("; break;
825 case Instruction::FAdd: Out << "getFAdd("; break;
826 case Instruction::Sub: Out << "getSub("; break;
827 case Instruction::FSub: Out << "getFSub("; break;
828 case Instruction::Mul: Out << "getMul("; break;
829 case Instruction::FMul: Out << "getFMul("; break;
830 case Instruction::UDiv: Out << "getUDiv("; break;
831 case Instruction::SDiv: Out << "getSDiv("; break;
832 case Instruction::FDiv: Out << "getFDiv("; break;
833 case Instruction::URem: Out << "getURem("; break;
834 case Instruction::SRem: Out << "getSRem("; break;
835 case Instruction::FRem: Out << "getFRem("; break;
836 case Instruction::And: Out << "getAnd("; break;
837 case Instruction::Or: Out << "getOr("; break;
838 case Instruction::Xor: Out << "getXor("; break;
839 case Instruction::ICmp:
840 Out << "getICmp(ICmpInst::ICMP_";
841 switch (CE->getPredicate()) {
842 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
843 case ICmpInst::ICMP_NE: Out << "NE"; break;
844 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
845 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
846 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
847 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
848 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
849 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
850 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
851 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
852 default: error("Invalid ICmp Predicate");
855 case Instruction::FCmp:
856 Out << "getFCmp(FCmpInst::FCMP_";
857 switch (CE->getPredicate()) {
858 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
859 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
860 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
861 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
862 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
863 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
864 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
865 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
866 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
867 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
868 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
869 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
870 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
871 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
872 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
873 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
874 default: error("Invalid FCmp Predicate");
877 case Instruction::Shl: Out << "getShl("; break;
878 case Instruction::LShr: Out << "getLShr("; break;
879 case Instruction::AShr: Out << "getAShr("; break;
880 case Instruction::Select: Out << "getSelect("; break;
881 case Instruction::ExtractElement: Out << "getExtractElement("; break;
882 case Instruction::InsertElement: Out << "getInsertElement("; break;
883 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
885 error("Invalid constant expression");
888 Out << getCppName(CE->getOperand(0));
889 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
890 Out << ", " << getCppName(CE->getOperand(i));
893 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
894 Out << "Constant* " << constName << " = ";
895 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
897 error("Bad Constant");
898 Out << "Constant* " << constName << " = 0; ";
903 void 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 const Constant *Init = GV->getInitializer();
934 printType(Init->getType());
935 if (const Function *F = dyn_cast<Function>(Init)) {
936 nl(Out)<< "/ Function Declarations"; nl(Out);
937 printFunctionHead(F);
938 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
939 nl(Out) << "// Global Variable Declarations"; nl(Out);
940 printVariableHead(gv);
942 nl(Out) << "// Global Variable Definitions"; nl(Out);
943 printVariableBody(gv);
945 nl(Out) << "// Constant Definitions"; nl(Out);
951 void CppWriter::printVariableHead(const GlobalVariable *GV) {
952 nl(Out) << "GlobalVariable* " << getCppName(GV);
954 Out << " = mod->getGlobalVariable(mod->getContext(), ";
955 printEscapedString(GV->getName());
956 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
957 nl(Out) << "if (!" << getCppName(GV) << ") {";
958 in(); nl(Out) << getCppName(GV);
960 Out << " = new GlobalVariable(/*Module=*/*mod, ";
961 nl(Out) << "/*Type=*/";
962 printCppName(GV->getType()->getElementType());
964 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
966 nl(Out) << "/*Linkage=*/";
967 printLinkageType(GV->getLinkage());
969 nl(Out) << "/*Initializer=*/0, ";
970 if (GV->hasInitializer()) {
971 Out << "// has initializer, specified below";
973 nl(Out) << "/*Name=*/\"";
974 printEscapedString(GV->getName());
978 if (GV->hasSection()) {
980 Out << "->setSection(\"";
981 printEscapedString(GV->getSection());
985 if (GV->getAlignment()) {
987 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
990 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
992 Out << "->setVisibility(";
993 printVisibilityType(GV->getVisibility());
997 if (GV->isThreadLocal()) {
999 Out << "->setThreadLocal(true);";
1003 out(); Out << "}"; nl(Out);
1007 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1008 if (GV->hasInitializer()) {
1010 Out << "->setInitializer(";
1011 Out << getCppName(GV->getInitializer()) << ");";
1016 std::string CppWriter::getOpName(const Value* V) {
1017 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1018 return getCppName(V);
1020 // See if its alread in the map of forward references, if so just return the
1021 // name we already set up for it
1022 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1023 if (I != ForwardRefs.end())
1026 // This is a new forward reference. Generate a unique name for it
1027 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1029 // Yes, this is a hack. An Argument is the smallest instantiable value that
1030 // we can make as a placeholder for the real value. We'll replace these
1031 // Argument instances later.
1032 Out << "Argument* " << result << " = new Argument("
1033 << getCppName(V->getType()) << ");";
1035 ForwardRefs[V] = result;
1039 static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1041 case NotAtomic: return "NotAtomic";
1042 case Unordered: return "Unordered";
1043 case Monotonic: return "Monotonic";
1044 case Acquire: return "Acquire";
1045 case Release: return "Release";
1046 case AcquireRelease: return "AcquireRelease";
1047 case SequentiallyConsistent: return "SequentiallyConsistent";
1049 llvm_unreachable("Unknown ordering");
1052 static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1053 switch (SynchScope) {
1054 case SingleThread: return "SingleThread";
1055 case CrossThread: return "CrossThread";
1057 llvm_unreachable("Unknown synch scope");
1060 // printInstruction - This member is called for each Instruction in a function.
1061 void CppWriter::printInstruction(const Instruction *I,
1062 const std::string& bbname) {
1063 std::string iName(getCppName(I));
1065 // Before we emit this instruction, we need to take care of generating any
1066 // forward references. So, we get the names of all the operands in advance
1067 const unsigned Ops(I->getNumOperands());
1068 std::string* opNames = new std::string[Ops];
1069 for (unsigned i = 0; i < Ops; i++)
1070 opNames[i] = getOpName(I->getOperand(i));
1072 switch (I->getOpcode()) {
1074 error("Invalid instruction");
1077 case Instruction::Ret: {
1078 const ReturnInst* ret = cast<ReturnInst>(I);
1079 Out << "ReturnInst::Create(mod->getContext(), "
1080 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1083 case Instruction::Br: {
1084 const BranchInst* br = cast<BranchInst>(I);
1085 Out << "BranchInst::Create(" ;
1086 if (br->getNumOperands() == 3) {
1087 Out << opNames[2] << ", "
1088 << opNames[1] << ", "
1089 << opNames[0] << ", ";
1091 } else if (br->getNumOperands() == 1) {
1092 Out << opNames[0] << ", ";
1094 error("Branch with 2 operands?");
1096 Out << bbname << ");";
1099 case Instruction::Switch: {
1100 const SwitchInst *SI = cast<SwitchInst>(I);
1101 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1102 << getOpName(SI->getCondition()) << ", "
1103 << getOpName(SI->getDefaultDest()) << ", "
1104 << SI->getNumCases() << ", " << bbname << ");";
1106 for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
1108 const ConstantInt* CaseVal = i.getCaseValue();
1109 const BasicBlock *BB = i.getCaseSuccessor();
1110 Out << iName << "->addCase("
1111 << getOpName(CaseVal) << ", "
1112 << getOpName(BB) << ");";
1117 case Instruction::IndirectBr: {
1118 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1119 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1120 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1122 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1123 Out << iName << "->addDestination(" << opNames[i] << ");";
1128 case Instruction::Resume: {
1129 Out << "ResumeInst::Create(mod->getContext(), " << opNames[0]
1130 << ", " << bbname << ");";
1133 case Instruction::Invoke: {
1134 const InvokeInst* inv = cast<InvokeInst>(I);
1135 Out << "std::vector<Value*> " << iName << "_params;";
1137 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1138 Out << iName << "_params.push_back("
1139 << getOpName(inv->getArgOperand(i)) << ");";
1142 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1143 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1144 << getOpName(inv->getCalledFunction()) << ", "
1145 << getOpName(inv->getNormalDest()) << ", "
1146 << getOpName(inv->getUnwindDest()) << ", "
1147 << iName << "_params, \"";
1148 printEscapedString(inv->getName());
1149 Out << "\", " << bbname << ");";
1150 nl(Out) << iName << "->setCallingConv(";
1151 printCallingConv(inv->getCallingConv());
1153 printAttributes(inv->getAttributes(), iName);
1154 Out << iName << "->setAttributes(" << iName << "_PAL);";
1158 case Instruction::Unreachable: {
1159 Out << "new UnreachableInst("
1160 << "mod->getContext(), "
1164 case Instruction::Add:
1165 case Instruction::FAdd:
1166 case Instruction::Sub:
1167 case Instruction::FSub:
1168 case Instruction::Mul:
1169 case Instruction::FMul:
1170 case Instruction::UDiv:
1171 case Instruction::SDiv:
1172 case Instruction::FDiv:
1173 case Instruction::URem:
1174 case Instruction::SRem:
1175 case Instruction::FRem:
1176 case Instruction::And:
1177 case Instruction::Or:
1178 case Instruction::Xor:
1179 case Instruction::Shl:
1180 case Instruction::LShr:
1181 case Instruction::AShr:{
1182 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1183 switch (I->getOpcode()) {
1184 case Instruction::Add: Out << "Instruction::Add"; break;
1185 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1186 case Instruction::Sub: Out << "Instruction::Sub"; break;
1187 case Instruction::FSub: Out << "Instruction::FSub"; break;
1188 case Instruction::Mul: Out << "Instruction::Mul"; break;
1189 case Instruction::FMul: Out << "Instruction::FMul"; break;
1190 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1191 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1192 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1193 case Instruction::URem:Out << "Instruction::URem"; break;
1194 case Instruction::SRem:Out << "Instruction::SRem"; break;
1195 case Instruction::FRem:Out << "Instruction::FRem"; break;
1196 case Instruction::And: Out << "Instruction::And"; break;
1197 case Instruction::Or: Out << "Instruction::Or"; break;
1198 case Instruction::Xor: Out << "Instruction::Xor"; break;
1199 case Instruction::Shl: Out << "Instruction::Shl"; break;
1200 case Instruction::LShr:Out << "Instruction::LShr"; break;
1201 case Instruction::AShr:Out << "Instruction::AShr"; break;
1202 default: Out << "Instruction::BadOpCode"; break;
1204 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1205 printEscapedString(I->getName());
1206 Out << "\", " << bbname << ");";
1209 case Instruction::FCmp: {
1210 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1211 switch (cast<FCmpInst>(I)->getPredicate()) {
1212 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1213 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1214 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1215 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1216 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1217 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1218 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1219 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1220 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1221 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1222 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1223 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1224 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1225 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1226 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1227 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1228 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1230 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1231 printEscapedString(I->getName());
1235 case Instruction::ICmp: {
1236 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1237 switch (cast<ICmpInst>(I)->getPredicate()) {
1238 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1239 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1240 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1241 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1242 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1243 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1244 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1245 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1246 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1247 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1248 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1250 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1251 printEscapedString(I->getName());
1255 case Instruction::Alloca: {
1256 const AllocaInst* allocaI = cast<AllocaInst>(I);
1257 Out << "AllocaInst* " << iName << " = new AllocaInst("
1258 << getCppName(allocaI->getAllocatedType()) << ", ";
1259 if (allocaI->isArrayAllocation())
1260 Out << opNames[0] << ", ";
1262 printEscapedString(allocaI->getName());
1263 Out << "\", " << bbname << ");";
1264 if (allocaI->getAlignment())
1265 nl(Out) << iName << "->setAlignment("
1266 << allocaI->getAlignment() << ");";
1269 case Instruction::Load: {
1270 const LoadInst* load = cast<LoadInst>(I);
1271 Out << "LoadInst* " << iName << " = new LoadInst("
1272 << opNames[0] << ", \"";
1273 printEscapedString(load->getName());
1274 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1275 << ", " << bbname << ");";
1276 if (load->getAlignment())
1277 nl(Out) << iName << "->setAlignment("
1278 << load->getAlignment() << ");";
1279 if (load->isAtomic()) {
1280 StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1281 StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1282 nl(Out) << iName << "->setAtomic("
1283 << Ordering << ", " << CrossThread << ");";
1287 case Instruction::Store: {
1288 const StoreInst* store = cast<StoreInst>(I);
1289 Out << "StoreInst* " << iName << " = new StoreInst("
1290 << opNames[0] << ", "
1291 << opNames[1] << ", "
1292 << (store->isVolatile() ? "true" : "false")
1293 << ", " << bbname << ");";
1294 if (store->getAlignment())
1295 nl(Out) << iName << "->setAlignment("
1296 << store->getAlignment() << ");";
1297 if (store->isAtomic()) {
1298 StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1299 StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1300 nl(Out) << iName << "->setAtomic("
1301 << Ordering << ", " << CrossThread << ");";
1305 case Instruction::GetElementPtr: {
1306 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1307 if (gep->getNumOperands() <= 2) {
1308 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1310 if (gep->getNumOperands() == 2)
1311 Out << ", " << opNames[1];
1313 Out << "std::vector<Value*> " << iName << "_indices;";
1315 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1316 Out << iName << "_indices.push_back("
1317 << opNames[i] << ");";
1320 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1321 << opNames[0] << ", " << iName << "_indices";
1324 printEscapedString(gep->getName());
1325 Out << "\", " << bbname << ");";
1328 case Instruction::PHI: {
1329 const PHINode* phi = cast<PHINode>(I);
1331 Out << "PHINode* " << iName << " = PHINode::Create("
1332 << getCppName(phi->getType()) << ", "
1333 << phi->getNumIncomingValues() << ", \"";
1334 printEscapedString(phi->getName());
1335 Out << "\", " << bbname << ");";
1337 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
1338 Out << iName << "->addIncoming("
1339 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
1340 << getOpName(phi->getIncomingBlock(i)) << ");";
1345 case Instruction::Trunc:
1346 case Instruction::ZExt:
1347 case Instruction::SExt:
1348 case Instruction::FPTrunc:
1349 case Instruction::FPExt:
1350 case Instruction::FPToUI:
1351 case Instruction::FPToSI:
1352 case Instruction::UIToFP:
1353 case Instruction::SIToFP:
1354 case Instruction::PtrToInt:
1355 case Instruction::IntToPtr:
1356 case Instruction::BitCast: {
1357 const CastInst* cst = cast<CastInst>(I);
1358 Out << "CastInst* " << iName << " = new ";
1359 switch (I->getOpcode()) {
1360 case Instruction::Trunc: Out << "TruncInst"; break;
1361 case Instruction::ZExt: Out << "ZExtInst"; break;
1362 case Instruction::SExt: Out << "SExtInst"; break;
1363 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1364 case Instruction::FPExt: Out << "FPExtInst"; break;
1365 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1366 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1367 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1368 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1369 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1370 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1371 case Instruction::BitCast: Out << "BitCastInst"; break;
1372 default: llvm_unreachable("Unreachable");
1374 Out << "(" << opNames[0] << ", "
1375 << getCppName(cst->getType()) << ", \"";
1376 printEscapedString(cst->getName());
1377 Out << "\", " << bbname << ");";
1380 case Instruction::Call: {
1381 const CallInst* call = cast<CallInst>(I);
1382 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1383 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1384 << getCppName(ila->getFunctionType()) << ", \""
1385 << ila->getAsmString() << "\", \""
1386 << ila->getConstraintString() << "\","
1387 << (ila->hasSideEffects() ? "true" : "false") << ");";
1390 if (call->getNumArgOperands() > 1) {
1391 Out << "std::vector<Value*> " << iName << "_params;";
1393 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
1394 Out << iName << "_params.push_back(" << opNames[i] << ");";
1397 Out << "CallInst* " << iName << " = CallInst::Create("
1398 << opNames[call->getNumArgOperands()] << ", "
1399 << iName << "_params, \"";
1400 } else if (call->getNumArgOperands() == 1) {
1401 Out << "CallInst* " << iName << " = CallInst::Create("
1402 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
1404 Out << "CallInst* " << iName << " = CallInst::Create("
1405 << opNames[call->getNumArgOperands()] << ", \"";
1407 printEscapedString(call->getName());
1408 Out << "\", " << bbname << ");";
1409 nl(Out) << iName << "->setCallingConv(";
1410 printCallingConv(call->getCallingConv());
1412 nl(Out) << iName << "->setTailCall("
1413 << (call->isTailCall() ? "true" : "false");
1416 printAttributes(call->getAttributes(), iName);
1417 Out << iName << "->setAttributes(" << iName << "_PAL);";
1421 case Instruction::Select: {
1422 const SelectInst* sel = cast<SelectInst>(I);
1423 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1424 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1425 printEscapedString(sel->getName());
1426 Out << "\", " << bbname << ");";
1429 case Instruction::UserOp1:
1431 case Instruction::UserOp2: {
1432 /// FIXME: What should be done here?
1435 case Instruction::VAArg: {
1436 const VAArgInst* va = cast<VAArgInst>(I);
1437 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1438 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1439 printEscapedString(va->getName());
1440 Out << "\", " << bbname << ");";
1443 case Instruction::ExtractElement: {
1444 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1445 Out << "ExtractElementInst* " << getCppName(eei)
1446 << " = new ExtractElementInst(" << opNames[0]
1447 << ", " << opNames[1] << ", \"";
1448 printEscapedString(eei->getName());
1449 Out << "\", " << bbname << ");";
1452 case Instruction::InsertElement: {
1453 const InsertElementInst* iei = cast<InsertElementInst>(I);
1454 Out << "InsertElementInst* " << getCppName(iei)
1455 << " = InsertElementInst::Create(" << opNames[0]
1456 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1457 printEscapedString(iei->getName());
1458 Out << "\", " << bbname << ");";
1461 case Instruction::ShuffleVector: {
1462 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1463 Out << "ShuffleVectorInst* " << getCppName(svi)
1464 << " = new ShuffleVectorInst(" << opNames[0]
1465 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1466 printEscapedString(svi->getName());
1467 Out << "\", " << bbname << ");";
1470 case Instruction::ExtractValue: {
1471 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1472 Out << "std::vector<unsigned> " << iName << "_indices;";
1474 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1475 Out << iName << "_indices.push_back("
1476 << evi->idx_begin()[i] << ");";
1479 Out << "ExtractValueInst* " << getCppName(evi)
1480 << " = ExtractValueInst::Create(" << opNames[0]
1482 << iName << "_indices, \"";
1483 printEscapedString(evi->getName());
1484 Out << "\", " << bbname << ");";
1487 case Instruction::InsertValue: {
1488 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1489 Out << "std::vector<unsigned> " << iName << "_indices;";
1491 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1492 Out << iName << "_indices.push_back("
1493 << ivi->idx_begin()[i] << ");";
1496 Out << "InsertValueInst* " << getCppName(ivi)
1497 << " = InsertValueInst::Create(" << opNames[0]
1498 << ", " << opNames[1] << ", "
1499 << iName << "_indices, \"";
1500 printEscapedString(ivi->getName());
1501 Out << "\", " << bbname << ");";
1504 case Instruction::Fence: {
1505 const FenceInst *fi = cast<FenceInst>(I);
1506 StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1507 StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1508 Out << "FenceInst* " << iName
1509 << " = new FenceInst(mod->getContext(), "
1510 << Ordering << ", " << CrossThread << ", " << bbname
1514 case Instruction::AtomicCmpXchg: {
1515 const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1516 StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1517 StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1518 Out << "AtomicCmpXchgInst* " << iName
1519 << " = new AtomicCmpXchgInst("
1520 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
1521 << Ordering << ", " << CrossThread << ", " << bbname
1523 nl(Out) << iName << "->setName(\"";
1524 printEscapedString(cxi->getName());
1528 case Instruction::AtomicRMW: {
1529 const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1530 StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1531 StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1532 StringRef Operation;
1533 switch (rmwi->getOperation()) {
1534 case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1535 case AtomicRMWInst::Add: Operation = "AtomicRMWInst::Add"; break;
1536 case AtomicRMWInst::Sub: Operation = "AtomicRMWInst::Sub"; break;
1537 case AtomicRMWInst::And: Operation = "AtomicRMWInst::And"; break;
1538 case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1539 case AtomicRMWInst::Or: Operation = "AtomicRMWInst::Or"; break;
1540 case AtomicRMWInst::Xor: Operation = "AtomicRMWInst::Xor"; break;
1541 case AtomicRMWInst::Max: Operation = "AtomicRMWInst::Max"; break;
1542 case AtomicRMWInst::Min: Operation = "AtomicRMWInst::Min"; break;
1543 case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1544 case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1545 case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1547 Out << "AtomicRMWInst* " << iName
1548 << " = new AtomicRMWInst("
1549 << Operation << ", "
1550 << opNames[0] << ", " << opNames[1] << ", "
1551 << Ordering << ", " << CrossThread << ", " << bbname
1553 nl(Out) << iName << "->setName(\"";
1554 printEscapedString(rmwi->getName());
1559 DefinedValues.insert(I);
1564 // Print out the types, constants and declarations needed by one function
1565 void CppWriter::printFunctionUses(const Function* F) {
1566 nl(Out) << "// Type Definitions"; nl(Out);
1568 // Print the function's return type
1569 printType(F->getReturnType());
1571 // Print the function's function type
1572 printType(F->getFunctionType());
1574 // Print the types of each of the function's arguments
1575 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1577 printType(AI->getType());
1581 // Print type definitions for every type referenced by an instruction and
1582 // make a note of any global values or constants that are referenced
1583 SmallPtrSet<GlobalValue*,64> gvs;
1584 SmallPtrSet<Constant*,64> consts;
1585 for (Function::const_iterator BB = F->begin(), BE = F->end();
1587 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1589 // Print the type of the instruction itself
1590 printType(I->getType());
1592 // Print the type of each of the instruction's operands
1593 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1594 Value* operand = I->getOperand(i);
1595 printType(operand->getType());
1597 // If the operand references a GVal or Constant, make a note of it
1598 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1600 if (GenerationType != GenFunction)
1601 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1602 if (GVar->hasInitializer())
1603 consts.insert(GVar->getInitializer());
1604 } else if (Constant* C = dyn_cast<Constant>(operand)) {
1606 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1607 // If the operand references a GVal or Constant, make a note of it
1608 Value* operand = C->getOperand(j);
1609 printType(operand->getType());
1610 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1612 if (GenerationType != GenFunction)
1613 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1614 if (GVar->hasInitializer())
1615 consts.insert(GVar->getInitializer());
1623 // Print the function declarations for any functions encountered
1624 nl(Out) << "// Function Declarations"; nl(Out);
1625 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1627 if (Function* Fun = dyn_cast<Function>(*I)) {
1628 if (!is_inline || Fun != F)
1629 printFunctionHead(Fun);
1633 // Print the global variable declarations for any variables encountered
1634 nl(Out) << "// Global Variable Declarations"; nl(Out);
1635 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1637 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1638 printVariableHead(F);
1641 // Print the constants found
1642 nl(Out) << "// Constant Definitions"; nl(Out);
1643 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1644 E = consts.end(); I != E; ++I) {
1648 // Process the global variables definitions now that all the constants have
1649 // been emitted. These definitions just couple the gvars with their constant
1651 if (GenerationType != GenFunction) {
1652 nl(Out) << "// Global Variable Definitions"; nl(Out);
1653 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1655 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1656 printVariableBody(GV);
1661 void CppWriter::printFunctionHead(const Function* F) {
1662 nl(Out) << "Function* " << getCppName(F);
1663 Out << " = mod->getFunction(\"";
1664 printEscapedString(F->getName());
1666 nl(Out) << "if (!" << getCppName(F) << ") {";
1667 nl(Out) << getCppName(F);
1669 Out<< " = Function::Create(";
1670 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1671 nl(Out) << "/*Linkage=*/";
1672 printLinkageType(F->getLinkage());
1674 nl(Out) << "/*Name=*/\"";
1675 printEscapedString(F->getName());
1676 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1679 Out << "->setCallingConv(";
1680 printCallingConv(F->getCallingConv());
1683 if (F->hasSection()) {
1685 Out << "->setSection(\"" << F->getSection() << "\");";
1688 if (F->getAlignment()) {
1690 Out << "->setAlignment(" << F->getAlignment() << ");";
1693 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1695 Out << "->setVisibility(";
1696 printVisibilityType(F->getVisibility());
1702 Out << "->setGC(\"" << F->getGC() << "\");";
1707 printAttributes(F->getAttributes(), getCppName(F));
1709 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1713 void CppWriter::printFunctionBody(const Function *F) {
1714 if (F->isDeclaration())
1715 return; // external functions have no bodies.
1717 // Clear the DefinedValues and ForwardRefs maps because we can't have
1718 // cross-function forward refs
1719 ForwardRefs.clear();
1720 DefinedValues.clear();
1722 // Create all the argument values
1724 if (!F->arg_empty()) {
1725 Out << "Function::arg_iterator args = " << getCppName(F)
1726 << "->arg_begin();";
1729 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1731 Out << "Value* " << getCppName(AI) << " = args++;";
1733 if (AI->hasName()) {
1734 Out << getCppName(AI) << "->setName(\"";
1735 printEscapedString(AI->getName());
1742 // Create all the basic blocks
1744 for (Function::const_iterator BI = F->begin(), BE = F->end();
1746 std::string bbname(getCppName(BI));
1747 Out << "BasicBlock* " << bbname <<
1748 " = BasicBlock::Create(mod->getContext(), \"";
1750 printEscapedString(BI->getName());
1751 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1755 // Output all of its basic blocks... for the function
1756 for (Function::const_iterator BI = F->begin(), BE = F->end();
1758 std::string bbname(getCppName(BI));
1759 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1762 // Output all of the instructions in the basic block...
1763 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1765 printInstruction(I,bbname);
1769 // Loop over the ForwardRefs and resolve them now that all instructions
1771 if (!ForwardRefs.empty()) {
1772 nl(Out) << "// Resolve Forward References";
1776 while (!ForwardRefs.empty()) {
1777 ForwardRefMap::iterator I = ForwardRefs.begin();
1778 Out << I->second << "->replaceAllUsesWith("
1779 << getCppName(I->first) << "); delete " << I->second << ";";
1781 ForwardRefs.erase(I);
1785 void CppWriter::printInline(const std::string& fname,
1786 const std::string& func) {
1787 const Function* F = TheModule->getFunction(func);
1789 error(std::string("Function '") + func + "' not found in input module");
1792 if (F->isDeclaration()) {
1793 error(std::string("Function '") + func + "' is external!");
1796 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1798 unsigned arg_count = 1;
1799 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1801 Out << ", Value* arg_" << arg_count;
1806 printFunctionUses(F);
1807 printFunctionBody(F);
1809 Out << "return " << getCppName(F->begin()) << ";";
1814 void CppWriter::printModuleBody() {
1815 // Print out all the type definitions
1816 nl(Out) << "// Type Definitions"; nl(Out);
1817 printTypes(TheModule);
1819 // Functions can call each other and global variables can reference them so
1820 // define all the functions first before emitting their function bodies.
1821 nl(Out) << "// Function Declarations"; nl(Out);
1822 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1824 printFunctionHead(I);
1826 // Process the global variables declarations. We can't initialze them until
1827 // after the constants are printed so just print a header for each global
1828 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1829 for (Module::const_global_iterator I = TheModule->global_begin(),
1830 E = TheModule->global_end(); I != E; ++I) {
1831 printVariableHead(I);
1834 // Print out all the constants definitions. Constants don't recurse except
1835 // through GlobalValues. All GlobalValues have been declared at this point
1836 // so we can proceed to generate the constants.
1837 nl(Out) << "// Constant Definitions"; nl(Out);
1838 printConstants(TheModule);
1840 // Process the global variables definitions now that all the constants have
1841 // been emitted. These definitions just couple the gvars with their constant
1843 nl(Out) << "// Global Variable Definitions"; nl(Out);
1844 for (Module::const_global_iterator I = TheModule->global_begin(),
1845 E = TheModule->global_end(); I != E; ++I) {
1846 printVariableBody(I);
1849 // Finally, we can safely put out all of the function bodies.
1850 nl(Out) << "// Function Definitions"; nl(Out);
1851 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1853 if (!I->isDeclaration()) {
1854 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1858 printFunctionBody(I);
1865 void CppWriter::printProgram(const std::string& fname,
1866 const std::string& mName) {
1867 Out << "#include <llvm/LLVMContext.h>\n";
1868 Out << "#include <llvm/Module.h>\n";
1869 Out << "#include <llvm/DerivedTypes.h>\n";
1870 Out << "#include <llvm/Constants.h>\n";
1871 Out << "#include <llvm/GlobalVariable.h>\n";
1872 Out << "#include <llvm/Function.h>\n";
1873 Out << "#include <llvm/CallingConv.h>\n";
1874 Out << "#include <llvm/BasicBlock.h>\n";
1875 Out << "#include <llvm/Instructions.h>\n";
1876 Out << "#include <llvm/InlineAsm.h>\n";
1877 Out << "#include <llvm/Support/FormattedStream.h>\n";
1878 Out << "#include <llvm/Support/MathExtras.h>\n";
1879 Out << "#include <llvm/Pass.h>\n";
1880 Out << "#include <llvm/PassManager.h>\n";
1881 Out << "#include <llvm/ADT/SmallVector.h>\n";
1882 Out << "#include <llvm/Analysis/Verifier.h>\n";
1883 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1884 Out << "#include <algorithm>\n";
1885 Out << "using namespace llvm;\n\n";
1886 Out << "Module* " << fname << "();\n\n";
1887 Out << "int main(int argc, char**argv) {\n";
1888 Out << " Module* Mod = " << fname << "();\n";
1889 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1890 Out << " PassManager PM;\n";
1891 Out << " PM.add(createPrintModulePass(&outs()));\n";
1892 Out << " PM.run(*Mod);\n";
1893 Out << " return 0;\n";
1895 printModule(fname,mName);
1898 void CppWriter::printModule(const std::string& fname,
1899 const std::string& mName) {
1900 nl(Out) << "Module* " << fname << "() {";
1901 nl(Out,1) << "// Module Construction";
1902 nl(Out) << "Module* mod = new Module(\"";
1903 printEscapedString(mName);
1904 Out << "\", getGlobalContext());";
1905 if (!TheModule->getTargetTriple().empty()) {
1906 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1908 if (!TheModule->getTargetTriple().empty()) {
1909 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1913 if (!TheModule->getModuleInlineAsm().empty()) {
1914 nl(Out) << "mod->setModuleInlineAsm(\"";
1915 printEscapedString(TheModule->getModuleInlineAsm());
1920 // Loop over the dependent libraries and emit them.
1921 Module::lib_iterator LI = TheModule->lib_begin();
1922 Module::lib_iterator LE = TheModule->lib_end();
1924 Out << "mod->addLibrary(\"" << *LI << "\");";
1929 nl(Out) << "return mod;";
1934 void CppWriter::printContents(const std::string& fname,
1935 const std::string& mName) {
1936 Out << "\nModule* " << fname << "(Module *mod) {\n";
1937 Out << "\nmod->setModuleIdentifier(\"";
1938 printEscapedString(mName);
1941 Out << "\nreturn mod;\n";
1945 void CppWriter::printFunction(const std::string& fname,
1946 const std::string& funcName) {
1947 const Function* F = TheModule->getFunction(funcName);
1949 error(std::string("Function '") + funcName + "' not found in input module");
1952 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1953 printFunctionUses(F);
1954 printFunctionHead(F);
1955 printFunctionBody(F);
1956 Out << "return " << getCppName(F) << ";\n";
1960 void CppWriter::printFunctions() {
1961 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1962 Module::const_iterator I = funcs.begin();
1963 Module::const_iterator IE = funcs.end();
1965 for (; I != IE; ++I) {
1966 const Function &func = *I;
1967 if (!func.isDeclaration()) {
1968 std::string name("define_");
1969 name += func.getName();
1970 printFunction(name, func.getName());
1975 void CppWriter::printVariable(const std::string& fname,
1976 const std::string& varName) {
1977 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1980 error(std::string("Variable '") + varName + "' not found in input module");
1983 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1984 printVariableUses(GV);
1985 printVariableHead(GV);
1986 printVariableBody(GV);
1987 Out << "return " << getCppName(GV) << ";\n";
1991 void CppWriter::printType(const std::string &fname,
1992 const std::string &typeName) {
1993 Type* Ty = TheModule->getTypeByName(typeName);
1995 error(std::string("Type '") + typeName + "' not found in input module");
1998 Out << "\nType* " << fname << "(Module *mod) {\n";
2000 Out << "return " << getCppName(Ty) << ";\n";
2004 bool CppWriter::runOnModule(Module &M) {
2008 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2010 // Get the name of the function we're supposed to generate
2011 std::string fname = FuncName.getValue();
2013 // Get the name of the thing we are to generate
2014 std::string tgtname = NameToGenerate.getValue();
2015 if (GenerationType == GenModule ||
2016 GenerationType == GenContents ||
2017 GenerationType == GenProgram ||
2018 GenerationType == GenFunctions) {
2019 if (tgtname == "!bad!") {
2020 if (M.getModuleIdentifier() == "-")
2021 tgtname = "<stdin>";
2023 tgtname = M.getModuleIdentifier();
2025 } else if (tgtname == "!bad!")
2026 error("You must use the -for option with -gen-{function,variable,type}");
2028 switch (WhatToGenerate(GenerationType)) {
2031 fname = "makeLLVMModule";
2032 printProgram(fname,tgtname);
2036 fname = "makeLLVMModule";
2037 printModule(fname,tgtname);
2041 fname = "makeLLVMModuleContents";
2042 printContents(fname,tgtname);
2046 fname = "makeLLVMFunction";
2047 printFunction(fname,tgtname);
2054 fname = "makeLLVMInline";
2055 printInline(fname,tgtname);
2059 fname = "makeLLVMVariable";
2060 printVariable(fname,tgtname);
2064 fname = "makeLLVMType";
2065 printType(fname,tgtname);
2072 char CppWriter::ID = 0;
2074 //===----------------------------------------------------------------------===//
2075 // External Interface declaration
2076 //===----------------------------------------------------------------------===//
2078 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2079 formatted_raw_ostream &o,
2080 CodeGenFileType FileType,
2081 bool DisableVerify) {
2082 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
2083 PM.add(new CppWriter(o));