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/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Config/config.h"
19 #include "llvm/IR/CallingConv.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Pass.h"
30 #include "llvm/PassManager.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/TargetRegistry.h"
42 static cl::opt<std::string>
43 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
44 cl::value_desc("function name"));
57 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
58 cl::desc("Choose what kind of output to generate"),
61 clEnumValN(GenProgram, "program", "Generate a complete program"),
62 clEnumValN(GenModule, "module", "Generate a module definition"),
63 clEnumValN(GenContents, "contents", "Generate contents of a module"),
64 clEnumValN(GenFunction, "function", "Generate a function definition"),
65 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
66 clEnumValN(GenInline, "inline", "Generate an inline function"),
67 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
68 clEnumValN(GenType, "type", "Generate a type definition"),
73 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
74 cl::desc("Specify the name of the thing to generate"),
77 extern "C" void LLVMInitializeCppBackendTarget() {
78 // Register the target.
79 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
83 typedef std::vector<Type*> TypeList;
84 typedef std::map<Type*,std::string> TypeMap;
85 typedef std::map<const Value*,std::string> ValueMap;
86 typedef std::set<std::string> NameSet;
87 typedef std::set<Type*> TypeSet;
88 typedef std::set<const Value*> ValueSet;
89 typedef std::map<const Value*,std::string> ForwardRefMap;
91 /// CppWriter - This class is the main chunk of code that converts an LLVM
92 /// module to a C++ translation unit.
93 class CppWriter : public ModulePass {
94 formatted_raw_ostream &Out;
95 const Module *TheModule;
100 TypeSet DefinedTypes;
101 ValueSet DefinedValues;
102 ForwardRefMap ForwardRefs;
104 unsigned indent_level;
108 explicit CppWriter(formatted_raw_ostream &o) :
109 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
111 virtual const char *getPassName() const { return "C++ backend"; }
113 bool runOnModule(Module &M);
115 void printProgram(const std::string& fname, const std::string& modName );
116 void printModule(const std::string& fname, const std::string& modName );
117 void printContents(const std::string& fname, const std::string& modName );
118 void printFunction(const std::string& fname, const std::string& funcName );
119 void printFunctions();
120 void printInline(const std::string& fname, const std::string& funcName );
121 void printVariable(const std::string& fname, const std::string& varName );
122 void printType(const std::string& fname, const std::string& typeName );
124 void error(const std::string& msg);
127 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
128 inline void in() { indent_level++; }
129 inline void out() { if (indent_level >0) indent_level--; }
132 void printLinkageType(GlobalValue::LinkageTypes LT);
133 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
134 void printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM);
135 void printCallingConv(CallingConv::ID cc);
136 void printEscapedString(const std::string& str);
137 void printCFP(const ConstantFP* CFP);
139 std::string getCppName(Type* val);
140 inline void printCppName(Type* val);
142 std::string getCppName(const Value* val);
143 inline void printCppName(const Value* val);
145 void printAttributes(const AttributeSet &PAL, const std::string &name);
146 void printType(Type* Ty);
147 void printTypes(const Module* M);
149 void printConstant(const Constant *CPV);
150 void printConstants(const Module* M);
152 void printVariableUses(const GlobalVariable *GV);
153 void printVariableHead(const GlobalVariable *GV);
154 void printVariableBody(const GlobalVariable *GV);
156 void printFunctionUses(const Function *F);
157 void printFunctionHead(const Function *F);
158 void printFunctionBody(const Function *F);
159 void printInstruction(const Instruction *I, const std::string& bbname);
160 std::string getOpName(const Value*);
162 void printModuleBody();
164 } // end anonymous namespace.
166 formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
168 if (delta >= 0 || indent_level >= unsigned(-delta))
169 indent_level += delta;
170 Out.indent(indent_level);
174 static inline void sanitize(std::string &str) {
175 for (size_t i = 0; i < str.length(); ++i)
176 if (!isalnum(str[i]) && str[i] != '_')
180 static std::string getTypePrefix(Type *Ty) {
181 switch (Ty->getTypeID()) {
182 case Type::VoidTyID: return "void_";
183 case Type::IntegerTyID:
184 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
185 case Type::FloatTyID: return "float_";
186 case Type::DoubleTyID: return "double_";
187 case Type::LabelTyID: return "label_";
188 case Type::FunctionTyID: return "func_";
189 case Type::StructTyID: return "struct_";
190 case Type::ArrayTyID: return "array_";
191 case Type::PointerTyID: return "ptr_";
192 case Type::VectorTyID: return "packed_";
193 default: return "other_";
197 void CppWriter::error(const std::string& msg) {
198 report_fatal_error(msg);
201 static inline std::string ftostr(const APFloat& V) {
203 if (&V.getSemantics() == &APFloat::IEEEdouble) {
204 raw_string_ostream(Buf) << V.convertToDouble();
206 } else if (&V.getSemantics() == &APFloat::IEEEsingle) {
207 raw_string_ostream(Buf) << (double)V.convertToFloat();
210 return "<unknown format in ftostr>"; // error
213 // printCFP - Print a floating point constant .. very carefully :)
214 // This makes sure that conversion to/from floating yields the same binary
215 // result so that we don't lose precision.
216 void CppWriter::printCFP(const ConstantFP *CFP) {
218 APFloat APF = APFloat(CFP->getValueAPF()); // copy
219 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
220 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
221 Out << "ConstantFP::get(mod->getContext(), ";
225 sprintf(Buffer, "%A", APF.convertToDouble());
226 if ((!strncmp(Buffer, "0x", 2) ||
227 !strncmp(Buffer, "-0x", 3) ||
228 !strncmp(Buffer, "+0x", 3)) &&
229 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
230 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
231 Out << "BitsToDouble(" << Buffer << ")";
233 Out << "BitsToFloat((float)" << Buffer << ")";
237 std::string StrVal = ftostr(CFP->getValueAPF());
239 while (StrVal[0] == ' ')
240 StrVal.erase(StrVal.begin());
242 // Check to make sure that the stringized number is not some string like
243 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
244 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
245 ((StrVal[0] == '-' || StrVal[0] == '+') &&
246 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
247 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
248 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
251 Out << StrVal << "f";
252 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
253 Out << "BitsToDouble(0x"
254 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
255 << "ULL) /* " << StrVal << " */";
257 Out << "BitsToFloat(0x"
258 << utohexstr((uint32_t)CFP->getValueAPF().
259 bitcastToAPInt().getZExtValue())
260 << "U) /* " << StrVal << " */";
268 void CppWriter::printCallingConv(CallingConv::ID cc){
269 // Print the calling convention.
271 case CallingConv::C: Out << "CallingConv::C"; break;
272 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
273 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
274 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
275 default: Out << cc; break;
279 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
281 case GlobalValue::InternalLinkage:
282 Out << "GlobalValue::InternalLinkage"; break;
283 case GlobalValue::PrivateLinkage:
284 Out << "GlobalValue::PrivateLinkage"; break;
285 case GlobalValue::LinkerPrivateLinkage:
286 Out << "GlobalValue::LinkerPrivateLinkage"; break;
287 case GlobalValue::LinkerPrivateWeakLinkage:
288 Out << "GlobalValue::LinkerPrivateWeakLinkage"; 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 void CppWriter::printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM) {
330 case GlobalVariable::NotThreadLocal:
331 Out << "GlobalVariable::NotThreadLocal";
333 case GlobalVariable::GeneralDynamicTLSModel:
334 Out << "GlobalVariable::GeneralDynamicTLSModel";
336 case GlobalVariable::LocalDynamicTLSModel:
337 Out << "GlobalVariable::LocalDynamicTLSModel";
339 case GlobalVariable::InitialExecTLSModel:
340 Out << "GlobalVariable::InitialExecTLSModel";
342 case GlobalVariable::LocalExecTLSModel:
343 Out << "GlobalVariable::LocalExecTLSModel";
348 // printEscapedString - Print each character of the specified string, escaping
349 // it if it is not printable or if it is an escape char.
350 void CppWriter::printEscapedString(const std::string &Str) {
351 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
352 unsigned char C = Str[i];
353 if (isprint(C) && C != '"' && C != '\\') {
357 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
358 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
363 std::string CppWriter::getCppName(Type* Ty) {
364 switch (Ty->getTypeID()) {
368 return "Type::getVoidTy(mod->getContext())";
369 case Type::IntegerTyID: {
370 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
371 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
373 case Type::X86_FP80TyID:
374 return "Type::getX86_FP80Ty(mod->getContext())";
375 case Type::FloatTyID:
376 return "Type::getFloatTy(mod->getContext())";
377 case Type::DoubleTyID:
378 return "Type::getDoubleTy(mod->getContext())";
379 case Type::LabelTyID:
380 return "Type::getLabelTy(mod->getContext())";
381 case Type::X86_MMXTyID:
382 return "Type::getX86_MMXTy(mod->getContext())";
385 // Now, see if we've seen the type before and return that
386 TypeMap::iterator I = TypeNames.find(Ty);
387 if (I != TypeNames.end())
390 // Okay, let's build a new name for this type. Start with a prefix
391 const char* prefix = 0;
392 switch (Ty->getTypeID()) {
393 case Type::FunctionTyID: prefix = "FuncTy_"; break;
394 case Type::StructTyID: prefix = "StructTy_"; break;
395 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
396 case Type::PointerTyID: prefix = "PointerTy_"; break;
397 case Type::VectorTyID: prefix = "VectorTy_"; break;
398 default: prefix = "OtherTy_"; break; // prevent breakage
401 // See if the type has a name in the symboltable and build accordingly
403 if (StructType *STy = dyn_cast<StructType>(Ty))
405 name = STy->getName();
408 name = utostr(uniqueNum++);
410 name = std::string(prefix) + name;
414 return TypeNames[Ty] = name;
417 void CppWriter::printCppName(Type* Ty) {
418 printEscapedString(getCppName(Ty));
421 std::string CppWriter::getCppName(const Value* val) {
423 ValueMap::iterator I = ValueNames.find(val);
424 if (I != ValueNames.end() && I->first == val)
427 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
428 name = std::string("gvar_") +
429 getTypePrefix(GV->getType()->getElementType());
430 } else if (isa<Function>(val)) {
431 name = std::string("func_");
432 } else if (const Constant* C = dyn_cast<Constant>(val)) {
433 name = std::string("const_") + getTypePrefix(C->getType());
434 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
436 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
437 Function::const_arg_iterator(Arg)) + 1;
438 name = std::string("arg_") + utostr(argNum);
439 NameSet::iterator NI = UsedNames.find(name);
440 if (NI != UsedNames.end())
441 name += std::string("_") + utostr(uniqueNum++);
442 UsedNames.insert(name);
443 return ValueNames[val] = name;
445 name = getTypePrefix(val->getType());
448 name = getTypePrefix(val->getType());
451 name += val->getName();
453 name += utostr(uniqueNum++);
455 NameSet::iterator NI = UsedNames.find(name);
456 if (NI != UsedNames.end())
457 name += std::string("_") + utostr(uniqueNum++);
458 UsedNames.insert(name);
459 return ValueNames[val] = name;
462 void CppWriter::printCppName(const Value* val) {
463 printEscapedString(getCppName(val));
466 void CppWriter::printAttributes(const AttributeSet &PAL,
467 const std::string &name) {
468 Out << "AttributeSet " << name << "_PAL;";
470 if (!PAL.isEmpty()) {
471 Out << '{'; in(); nl(Out);
472 Out << "SmallVector<AttributeSet, 4> Attrs;"; nl(Out);
473 Out << "AttributeSet PAS;"; in(); nl(Out);
474 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
475 unsigned index = PAL.getSlotIndex(i);
476 AttrBuilder attrs(PAL.getSlotAttributes(i), index);
477 Out << "{"; in(); nl(Out);
478 Out << "AttrBuilder B;"; nl(Out);
480 #define HANDLE_ATTR(X) \
481 if (attrs.contains(Attribute::X)) { \
482 Out << "B.addAttribute(Attribute::" #X ");"; nl(Out); \
483 attrs.removeAttribute(Attribute::X); \
488 HANDLE_ATTR(NoReturn);
490 HANDLE_ATTR(StructRet);
491 HANDLE_ATTR(NoUnwind);
492 HANDLE_ATTR(NoAlias);
494 HANDLE_ATTR(InAlloca);
496 HANDLE_ATTR(ReadNone);
497 HANDLE_ATTR(ReadOnly);
498 HANDLE_ATTR(NoInline);
499 HANDLE_ATTR(AlwaysInline);
500 HANDLE_ATTR(OptimizeNone);
501 HANDLE_ATTR(OptimizeForSize);
502 HANDLE_ATTR(StackProtect);
503 HANDLE_ATTR(StackProtectReq);
504 HANDLE_ATTR(StackProtectStrong);
505 HANDLE_ATTR(NoCapture);
506 HANDLE_ATTR(NoRedZone);
507 HANDLE_ATTR(NoImplicitFloat);
509 HANDLE_ATTR(InlineHint);
510 HANDLE_ATTR(ReturnsTwice);
511 HANDLE_ATTR(UWTable);
512 HANDLE_ATTR(NonLazyBind);
513 HANDLE_ATTR(MinSize);
516 if (attrs.contains(Attribute::StackAlignment)) {
517 Out << "B.addStackAlignmentAttr(" << attrs.getStackAlignment()<<')';
519 attrs.removeAttribute(Attribute::StackAlignment);
522 Out << "PAS = AttributeSet::get(mod->getContext(), ";
526 Out << index << "U,";
527 Out << " B);"; out(); nl(Out);
528 Out << "}"; out(); nl(Out);
530 Out << "Attrs.push_back(PAS);"; nl(Out);
532 Out << name << "_PAL = AttributeSet::get(mod->getContext(), Attrs);";
539 void CppWriter::printType(Type* Ty) {
540 // We don't print definitions for primitive types
541 if (Ty->isFloatingPointTy() || Ty->isX86_MMXTy() || Ty->isIntegerTy() ||
542 Ty->isLabelTy() || Ty->isMetadataTy() || Ty->isVoidTy())
545 // If we already defined this type, we don't need to define it again.
546 if (DefinedTypes.find(Ty) != DefinedTypes.end())
549 // Everything below needs the name for the type so get it now.
550 std::string typeName(getCppName(Ty));
552 // Print the type definition
553 switch (Ty->getTypeID()) {
554 case Type::FunctionTyID: {
555 FunctionType* FT = cast<FunctionType>(Ty);
556 Out << "std::vector<Type*>" << typeName << "_args;";
558 FunctionType::param_iterator PI = FT->param_begin();
559 FunctionType::param_iterator PE = FT->param_end();
560 for (; PI != PE; ++PI) {
561 Type* argTy = static_cast<Type*>(*PI);
563 std::string argName(getCppName(argTy));
564 Out << typeName << "_args.push_back(" << argName;
568 printType(FT->getReturnType());
569 std::string retTypeName(getCppName(FT->getReturnType()));
570 Out << "FunctionType* " << typeName << " = FunctionType::get(";
571 in(); nl(Out) << "/*Result=*/" << retTypeName;
573 nl(Out) << "/*Params=*/" << typeName << "_args,";
574 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
579 case Type::StructTyID: {
580 StructType* ST = cast<StructType>(Ty);
581 if (!ST->isLiteral()) {
582 Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
583 printEscapedString(ST->getName());
586 Out << "if (!" << typeName << ") {";
588 Out << typeName << " = ";
589 Out << "StructType::create(mod->getContext(), \"";
590 printEscapedString(ST->getName());
595 // Indicate that this type is now defined.
596 DefinedTypes.insert(Ty);
599 Out << "std::vector<Type*>" << typeName << "_fields;";
601 StructType::element_iterator EI = ST->element_begin();
602 StructType::element_iterator EE = ST->element_end();
603 for (; EI != EE; ++EI) {
604 Type* fieldTy = static_cast<Type*>(*EI);
606 std::string fieldName(getCppName(fieldTy));
607 Out << typeName << "_fields.push_back(" << fieldName;
612 if (ST->isLiteral()) {
613 Out << "StructType *" << typeName << " = ";
614 Out << "StructType::get(" << "mod->getContext(), ";
616 Out << "if (" << typeName << "->isOpaque()) {";
618 Out << typeName << "->setBody(";
621 Out << typeName << "_fields, /*isPacked=*/"
622 << (ST->isPacked() ? "true" : "false") << ");";
624 if (!ST->isLiteral()) {
630 case Type::ArrayTyID: {
631 ArrayType* AT = cast<ArrayType>(Ty);
632 Type* ET = AT->getElementType();
634 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
635 std::string elemName(getCppName(ET));
636 Out << "ArrayType* " << typeName << " = ArrayType::get("
638 << ", " << utostr(AT->getNumElements()) << ");";
643 case Type::PointerTyID: {
644 PointerType* PT = cast<PointerType>(Ty);
645 Type* ET = PT->getElementType();
647 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
648 std::string elemName(getCppName(ET));
649 Out << "PointerType* " << typeName << " = PointerType::get("
651 << ", " << utostr(PT->getAddressSpace()) << ");";
656 case Type::VectorTyID: {
657 VectorType* PT = cast<VectorType>(Ty);
658 Type* ET = PT->getElementType();
660 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
661 std::string elemName(getCppName(ET));
662 Out << "VectorType* " << typeName << " = VectorType::get("
664 << ", " << utostr(PT->getNumElements()) << ");";
670 error("Invalid TypeID");
673 // Indicate that this type is now defined.
674 DefinedTypes.insert(Ty);
676 // Finally, separate the type definition from other with a newline.
680 void CppWriter::printTypes(const Module* M) {
681 // Add all of the global variables to the value table.
682 for (Module::const_global_iterator I = TheModule->global_begin(),
683 E = TheModule->global_end(); I != E; ++I) {
684 if (I->hasInitializer())
685 printType(I->getInitializer()->getType());
686 printType(I->getType());
689 // Add all the functions to the table
690 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
692 printType(FI->getReturnType());
693 printType(FI->getFunctionType());
694 // Add all the function arguments
695 for (Function::const_arg_iterator AI = FI->arg_begin(),
696 AE = FI->arg_end(); AI != AE; ++AI) {
697 printType(AI->getType());
700 // Add all of the basic blocks and instructions
701 for (Function::const_iterator BB = FI->begin(),
702 E = FI->end(); BB != E; ++BB) {
703 printType(BB->getType());
704 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
706 printType(I->getType());
707 for (unsigned i = 0; i < I->getNumOperands(); ++i)
708 printType(I->getOperand(i)->getType());
715 // printConstant - Print out a constant pool entry...
716 void CppWriter::printConstant(const Constant *CV) {
717 // First, if the constant is actually a GlobalValue (variable or function)
718 // or its already in the constant list then we've printed it already and we
720 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
723 std::string constName(getCppName(CV));
724 std::string typeName(getCppName(CV->getType()));
726 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
727 std::string constValue = CI->getValue().toString(10, true);
728 Out << "ConstantInt* " << constName
729 << " = ConstantInt::get(mod->getContext(), APInt("
730 << cast<IntegerType>(CI->getType())->getBitWidth()
731 << ", StringRef(\"" << constValue << "\"), 10));";
732 } else if (isa<ConstantAggregateZero>(CV)) {
733 Out << "ConstantAggregateZero* " << constName
734 << " = ConstantAggregateZero::get(" << typeName << ");";
735 } else if (isa<ConstantPointerNull>(CV)) {
736 Out << "ConstantPointerNull* " << constName
737 << " = ConstantPointerNull::get(" << typeName << ");";
738 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
739 Out << "ConstantFP* " << constName << " = ";
742 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
743 Out << "std::vector<Constant*> " << constName << "_elems;";
745 unsigned N = CA->getNumOperands();
746 for (unsigned i = 0; i < N; ++i) {
747 printConstant(CA->getOperand(i)); // recurse to print operands
748 Out << constName << "_elems.push_back("
749 << getCppName(CA->getOperand(i)) << ");";
752 Out << "Constant* " << constName << " = ConstantArray::get("
753 << typeName << ", " << constName << "_elems);";
754 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
755 Out << "std::vector<Constant*> " << constName << "_fields;";
757 unsigned N = CS->getNumOperands();
758 for (unsigned i = 0; i < N; i++) {
759 printConstant(CS->getOperand(i));
760 Out << constName << "_fields.push_back("
761 << getCppName(CS->getOperand(i)) << ");";
764 Out << "Constant* " << constName << " = ConstantStruct::get("
765 << typeName << ", " << constName << "_fields);";
766 } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
767 Out << "std::vector<Constant*> " << constName << "_elems;";
769 unsigned N = CVec->getNumOperands();
770 for (unsigned i = 0; i < N; ++i) {
771 printConstant(CVec->getOperand(i));
772 Out << constName << "_elems.push_back("
773 << getCppName(CVec->getOperand(i)) << ");";
776 Out << "Constant* " << constName << " = ConstantVector::get("
777 << typeName << ", " << constName << "_elems);";
778 } else if (isa<UndefValue>(CV)) {
779 Out << "UndefValue* " << constName << " = UndefValue::get("
781 } else if (const ConstantDataSequential *CDS =
782 dyn_cast<ConstantDataSequential>(CV)) {
783 if (CDS->isString()) {
784 Out << "Constant *" << constName <<
785 " = ConstantDataArray::getString(mod->getContext(), \"";
786 StringRef Str = CDS->getAsString();
787 bool nullTerminate = false;
788 if (Str.back() == 0) {
789 Str = Str.drop_back();
790 nullTerminate = true;
792 printEscapedString(Str);
793 // Determine if we want null termination or not.
797 Out << "\", false);";// No null terminator
799 // TODO: Could generate more efficient code generating CDS calls instead.
800 Out << "std::vector<Constant*> " << constName << "_elems;";
802 for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
803 Constant *Elt = CDS->getElementAsConstant(i);
805 Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
808 Out << "Constant* " << constName;
810 if (isa<ArrayType>(CDS->getType()))
811 Out << " = ConstantArray::get(";
813 Out << " = ConstantVector::get(";
814 Out << typeName << ", " << constName << "_elems);";
816 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
817 if (CE->getOpcode() == Instruction::GetElementPtr) {
818 Out << "std::vector<Constant*> " << constName << "_indices;";
820 printConstant(CE->getOperand(0));
821 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
822 printConstant(CE->getOperand(i));
823 Out << constName << "_indices.push_back("
824 << getCppName(CE->getOperand(i)) << ");";
827 Out << "Constant* " << constName
828 << " = ConstantExpr::getGetElementPtr("
829 << getCppName(CE->getOperand(0)) << ", "
830 << constName << "_indices);";
831 } else if (CE->isCast()) {
832 printConstant(CE->getOperand(0));
833 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
834 switch (CE->getOpcode()) {
835 default: llvm_unreachable("Invalid cast opcode");
836 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
837 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
838 case Instruction::SExt: Out << "Instruction::SExt"; break;
839 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
840 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
841 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
842 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
843 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
844 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
845 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
846 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
847 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
849 Out << ", " << getCppName(CE->getOperand(0)) << ", "
850 << getCppName(CE->getType()) << ");";
852 unsigned N = CE->getNumOperands();
853 for (unsigned i = 0; i < N; ++i ) {
854 printConstant(CE->getOperand(i));
856 Out << "Constant* " << constName << " = ConstantExpr::";
857 switch (CE->getOpcode()) {
858 case Instruction::Add: Out << "getAdd("; break;
859 case Instruction::FAdd: Out << "getFAdd("; break;
860 case Instruction::Sub: Out << "getSub("; break;
861 case Instruction::FSub: Out << "getFSub("; break;
862 case Instruction::Mul: Out << "getMul("; break;
863 case Instruction::FMul: Out << "getFMul("; break;
864 case Instruction::UDiv: Out << "getUDiv("; break;
865 case Instruction::SDiv: Out << "getSDiv("; break;
866 case Instruction::FDiv: Out << "getFDiv("; break;
867 case Instruction::URem: Out << "getURem("; break;
868 case Instruction::SRem: Out << "getSRem("; break;
869 case Instruction::FRem: Out << "getFRem("; break;
870 case Instruction::And: Out << "getAnd("; break;
871 case Instruction::Or: Out << "getOr("; break;
872 case Instruction::Xor: Out << "getXor("; break;
873 case Instruction::ICmp:
874 Out << "getICmp(ICmpInst::ICMP_";
875 switch (CE->getPredicate()) {
876 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
877 case ICmpInst::ICMP_NE: Out << "NE"; break;
878 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
879 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
880 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
881 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
882 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
883 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
884 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
885 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
886 default: error("Invalid ICmp Predicate");
889 case Instruction::FCmp:
890 Out << "getFCmp(FCmpInst::FCMP_";
891 switch (CE->getPredicate()) {
892 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
893 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
894 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
895 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
896 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
897 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
898 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
899 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
900 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
901 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
902 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
903 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
904 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
905 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
906 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
907 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
908 default: error("Invalid FCmp Predicate");
911 case Instruction::Shl: Out << "getShl("; break;
912 case Instruction::LShr: Out << "getLShr("; break;
913 case Instruction::AShr: Out << "getAShr("; break;
914 case Instruction::Select: Out << "getSelect("; break;
915 case Instruction::ExtractElement: Out << "getExtractElement("; break;
916 case Instruction::InsertElement: Out << "getInsertElement("; break;
917 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
919 error("Invalid constant expression");
922 Out << getCppName(CE->getOperand(0));
923 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
924 Out << ", " << getCppName(CE->getOperand(i));
927 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
928 Out << "Constant* " << constName << " = ";
929 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
931 error("Bad Constant");
932 Out << "Constant* " << constName << " = 0; ";
937 void CppWriter::printConstants(const Module* M) {
938 // Traverse all the global variables looking for constant initializers
939 for (Module::const_global_iterator I = TheModule->global_begin(),
940 E = TheModule->global_end(); I != E; ++I)
941 if (I->hasInitializer())
942 printConstant(I->getInitializer());
944 // Traverse the LLVM functions looking for constants
945 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
947 // Add all of the basic blocks and instructions
948 for (Function::const_iterator BB = FI->begin(),
949 E = FI->end(); BB != E; ++BB) {
950 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
952 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
953 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
962 void CppWriter::printVariableUses(const GlobalVariable *GV) {
963 nl(Out) << "// Type Definitions";
965 printType(GV->getType());
966 if (GV->hasInitializer()) {
967 const Constant *Init = GV->getInitializer();
968 printType(Init->getType());
969 if (const Function *F = dyn_cast<Function>(Init)) {
970 nl(Out)<< "/ Function Declarations"; nl(Out);
971 printFunctionHead(F);
972 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
973 nl(Out) << "// Global Variable Declarations"; nl(Out);
974 printVariableHead(gv);
976 nl(Out) << "// Global Variable Definitions"; nl(Out);
977 printVariableBody(gv);
979 nl(Out) << "// Constant Definitions"; nl(Out);
985 void CppWriter::printVariableHead(const GlobalVariable *GV) {
986 nl(Out) << "GlobalVariable* " << getCppName(GV);
988 Out << " = mod->getGlobalVariable(mod->getContext(), ";
989 printEscapedString(GV->getName());
990 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
991 nl(Out) << "if (!" << getCppName(GV) << ") {";
992 in(); nl(Out) << getCppName(GV);
994 Out << " = new GlobalVariable(/*Module=*/*mod, ";
995 nl(Out) << "/*Type=*/";
996 printCppName(GV->getType()->getElementType());
998 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1000 nl(Out) << "/*Linkage=*/";
1001 printLinkageType(GV->getLinkage());
1003 nl(Out) << "/*Initializer=*/0, ";
1004 if (GV->hasInitializer()) {
1005 Out << "// has initializer, specified below";
1007 nl(Out) << "/*Name=*/\"";
1008 printEscapedString(GV->getName());
1012 if (GV->hasSection()) {
1014 Out << "->setSection(\"";
1015 printEscapedString(GV->getSection());
1019 if (GV->getAlignment()) {
1021 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1024 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1026 Out << "->setVisibility(";
1027 printVisibilityType(GV->getVisibility());
1031 if (GV->isThreadLocal()) {
1033 Out << "->setThreadLocalMode(";
1034 printThreadLocalMode(GV->getThreadLocalMode());
1039 out(); Out << "}"; nl(Out);
1043 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1044 if (GV->hasInitializer()) {
1046 Out << "->setInitializer(";
1047 Out << getCppName(GV->getInitializer()) << ");";
1052 std::string CppWriter::getOpName(const Value* V) {
1053 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1054 return getCppName(V);
1056 // See if its alread in the map of forward references, if so just return the
1057 // name we already set up for it
1058 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1059 if (I != ForwardRefs.end())
1062 // This is a new forward reference. Generate a unique name for it
1063 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1065 // Yes, this is a hack. An Argument is the smallest instantiable value that
1066 // we can make as a placeholder for the real value. We'll replace these
1067 // Argument instances later.
1068 Out << "Argument* " << result << " = new Argument("
1069 << getCppName(V->getType()) << ");";
1071 ForwardRefs[V] = result;
1075 static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1077 case NotAtomic: return "NotAtomic";
1078 case Unordered: return "Unordered";
1079 case Monotonic: return "Monotonic";
1080 case Acquire: return "Acquire";
1081 case Release: return "Release";
1082 case AcquireRelease: return "AcquireRelease";
1083 case SequentiallyConsistent: return "SequentiallyConsistent";
1085 llvm_unreachable("Unknown ordering");
1088 static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1089 switch (SynchScope) {
1090 case SingleThread: return "SingleThread";
1091 case CrossThread: return "CrossThread";
1093 llvm_unreachable("Unknown synch scope");
1096 // printInstruction - This member is called for each Instruction in a function.
1097 void CppWriter::printInstruction(const Instruction *I,
1098 const std::string& bbname) {
1099 std::string iName(getCppName(I));
1101 // Before we emit this instruction, we need to take care of generating any
1102 // forward references. So, we get the names of all the operands in advance
1103 const unsigned Ops(I->getNumOperands());
1104 std::string* opNames = new std::string[Ops];
1105 for (unsigned i = 0; i < Ops; i++)
1106 opNames[i] = getOpName(I->getOperand(i));
1108 switch (I->getOpcode()) {
1110 error("Invalid instruction");
1113 case Instruction::Ret: {
1114 const ReturnInst* ret = cast<ReturnInst>(I);
1115 Out << "ReturnInst::Create(mod->getContext(), "
1116 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1119 case Instruction::Br: {
1120 const BranchInst* br = cast<BranchInst>(I);
1121 Out << "BranchInst::Create(" ;
1122 if (br->getNumOperands() == 3) {
1123 Out << opNames[2] << ", "
1124 << opNames[1] << ", "
1125 << opNames[0] << ", ";
1127 } else if (br->getNumOperands() == 1) {
1128 Out << opNames[0] << ", ";
1130 error("Branch with 2 operands?");
1132 Out << bbname << ");";
1135 case Instruction::Switch: {
1136 const SwitchInst *SI = cast<SwitchInst>(I);
1137 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1138 << getOpName(SI->getCondition()) << ", "
1139 << getOpName(SI->getDefaultDest()) << ", "
1140 << SI->getNumCases() << ", " << bbname << ");";
1142 for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
1144 const ConstantInt* CaseVal = i.getCaseValue();
1145 const BasicBlock *BB = i.getCaseSuccessor();
1146 Out << iName << "->addCase("
1147 << getOpName(CaseVal) << ", "
1148 << getOpName(BB) << ");";
1153 case Instruction::IndirectBr: {
1154 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1155 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1156 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1158 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1159 Out << iName << "->addDestination(" << opNames[i] << ");";
1164 case Instruction::Resume: {
1165 Out << "ResumeInst::Create(" << opNames[0] << ", " << bbname << ");";
1168 case Instruction::Invoke: {
1169 const InvokeInst* inv = cast<InvokeInst>(I);
1170 Out << "std::vector<Value*> " << iName << "_params;";
1172 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1173 Out << iName << "_params.push_back("
1174 << getOpName(inv->getArgOperand(i)) << ");";
1177 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1178 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1179 << getOpName(inv->getCalledValue()) << ", "
1180 << getOpName(inv->getNormalDest()) << ", "
1181 << getOpName(inv->getUnwindDest()) << ", "
1182 << iName << "_params, \"";
1183 printEscapedString(inv->getName());
1184 Out << "\", " << bbname << ");";
1185 nl(Out) << iName << "->setCallingConv(";
1186 printCallingConv(inv->getCallingConv());
1188 printAttributes(inv->getAttributes(), iName);
1189 Out << iName << "->setAttributes(" << iName << "_PAL);";
1193 case Instruction::Unreachable: {
1194 Out << "new UnreachableInst("
1195 << "mod->getContext(), "
1199 case Instruction::Add:
1200 case Instruction::FAdd:
1201 case Instruction::Sub:
1202 case Instruction::FSub:
1203 case Instruction::Mul:
1204 case Instruction::FMul:
1205 case Instruction::UDiv:
1206 case Instruction::SDiv:
1207 case Instruction::FDiv:
1208 case Instruction::URem:
1209 case Instruction::SRem:
1210 case Instruction::FRem:
1211 case Instruction::And:
1212 case Instruction::Or:
1213 case Instruction::Xor:
1214 case Instruction::Shl:
1215 case Instruction::LShr:
1216 case Instruction::AShr:{
1217 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1218 switch (I->getOpcode()) {
1219 case Instruction::Add: Out << "Instruction::Add"; break;
1220 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1221 case Instruction::Sub: Out << "Instruction::Sub"; break;
1222 case Instruction::FSub: Out << "Instruction::FSub"; break;
1223 case Instruction::Mul: Out << "Instruction::Mul"; break;
1224 case Instruction::FMul: Out << "Instruction::FMul"; break;
1225 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1226 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1227 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1228 case Instruction::URem:Out << "Instruction::URem"; break;
1229 case Instruction::SRem:Out << "Instruction::SRem"; break;
1230 case Instruction::FRem:Out << "Instruction::FRem"; break;
1231 case Instruction::And: Out << "Instruction::And"; break;
1232 case Instruction::Or: Out << "Instruction::Or"; break;
1233 case Instruction::Xor: Out << "Instruction::Xor"; break;
1234 case Instruction::Shl: Out << "Instruction::Shl"; break;
1235 case Instruction::LShr:Out << "Instruction::LShr"; break;
1236 case Instruction::AShr:Out << "Instruction::AShr"; break;
1237 default: Out << "Instruction::BadOpCode"; break;
1239 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1240 printEscapedString(I->getName());
1241 Out << "\", " << bbname << ");";
1244 case Instruction::FCmp: {
1245 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1246 switch (cast<FCmpInst>(I)->getPredicate()) {
1247 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1248 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1249 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1250 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1251 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1252 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1253 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1254 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1255 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1256 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1257 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1258 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1259 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1260 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1261 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1262 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1263 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1265 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1266 printEscapedString(I->getName());
1270 case Instruction::ICmp: {
1271 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1272 switch (cast<ICmpInst>(I)->getPredicate()) {
1273 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1274 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1275 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1276 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1277 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1278 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1279 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1280 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1281 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1282 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1283 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1285 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1286 printEscapedString(I->getName());
1290 case Instruction::Alloca: {
1291 const AllocaInst* allocaI = cast<AllocaInst>(I);
1292 Out << "AllocaInst* " << iName << " = new AllocaInst("
1293 << getCppName(allocaI->getAllocatedType()) << ", ";
1294 if (allocaI->isArrayAllocation())
1295 Out << opNames[0] << ", ";
1297 printEscapedString(allocaI->getName());
1298 Out << "\", " << bbname << ");";
1299 if (allocaI->getAlignment())
1300 nl(Out) << iName << "->setAlignment("
1301 << allocaI->getAlignment() << ");";
1304 case Instruction::Load: {
1305 const LoadInst* load = cast<LoadInst>(I);
1306 Out << "LoadInst* " << iName << " = new LoadInst("
1307 << opNames[0] << ", \"";
1308 printEscapedString(load->getName());
1309 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1310 << ", " << bbname << ");";
1311 if (load->getAlignment())
1312 nl(Out) << iName << "->setAlignment("
1313 << load->getAlignment() << ");";
1314 if (load->isAtomic()) {
1315 StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1316 StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1317 nl(Out) << iName << "->setAtomic("
1318 << Ordering << ", " << CrossThread << ");";
1322 case Instruction::Store: {
1323 const StoreInst* store = cast<StoreInst>(I);
1324 Out << "StoreInst* " << iName << " = new StoreInst("
1325 << opNames[0] << ", "
1326 << opNames[1] << ", "
1327 << (store->isVolatile() ? "true" : "false")
1328 << ", " << bbname << ");";
1329 if (store->getAlignment())
1330 nl(Out) << iName << "->setAlignment("
1331 << store->getAlignment() << ");";
1332 if (store->isAtomic()) {
1333 StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1334 StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1335 nl(Out) << iName << "->setAtomic("
1336 << Ordering << ", " << CrossThread << ");";
1340 case Instruction::GetElementPtr: {
1341 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1342 if (gep->getNumOperands() <= 2) {
1343 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1345 if (gep->getNumOperands() == 2)
1346 Out << ", " << opNames[1];
1348 Out << "std::vector<Value*> " << iName << "_indices;";
1350 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1351 Out << iName << "_indices.push_back("
1352 << opNames[i] << ");";
1355 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1356 << opNames[0] << ", " << iName << "_indices";
1359 printEscapedString(gep->getName());
1360 Out << "\", " << bbname << ");";
1363 case Instruction::PHI: {
1364 const PHINode* phi = cast<PHINode>(I);
1366 Out << "PHINode* " << iName << " = PHINode::Create("
1367 << getCppName(phi->getType()) << ", "
1368 << phi->getNumIncomingValues() << ", \"";
1369 printEscapedString(phi->getName());
1370 Out << "\", " << bbname << ");";
1372 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
1373 Out << iName << "->addIncoming("
1374 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
1375 << getOpName(phi->getIncomingBlock(i)) << ");";
1380 case Instruction::Trunc:
1381 case Instruction::ZExt:
1382 case Instruction::SExt:
1383 case Instruction::FPTrunc:
1384 case Instruction::FPExt:
1385 case Instruction::FPToUI:
1386 case Instruction::FPToSI:
1387 case Instruction::UIToFP:
1388 case Instruction::SIToFP:
1389 case Instruction::PtrToInt:
1390 case Instruction::IntToPtr:
1391 case Instruction::BitCast: {
1392 const CastInst* cst = cast<CastInst>(I);
1393 Out << "CastInst* " << iName << " = new ";
1394 switch (I->getOpcode()) {
1395 case Instruction::Trunc: Out << "TruncInst"; break;
1396 case Instruction::ZExt: Out << "ZExtInst"; break;
1397 case Instruction::SExt: Out << "SExtInst"; break;
1398 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1399 case Instruction::FPExt: Out << "FPExtInst"; break;
1400 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1401 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1402 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1403 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1404 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1405 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1406 case Instruction::BitCast: Out << "BitCastInst"; break;
1407 default: llvm_unreachable("Unreachable");
1409 Out << "(" << opNames[0] << ", "
1410 << getCppName(cst->getType()) << ", \"";
1411 printEscapedString(cst->getName());
1412 Out << "\", " << bbname << ");";
1415 case Instruction::Call: {
1416 const CallInst* call = cast<CallInst>(I);
1417 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1418 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1419 << getCppName(ila->getFunctionType()) << ", \""
1420 << ila->getAsmString() << "\", \""
1421 << ila->getConstraintString() << "\","
1422 << (ila->hasSideEffects() ? "true" : "false") << ");";
1425 if (call->getNumArgOperands() > 1) {
1426 Out << "std::vector<Value*> " << iName << "_params;";
1428 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
1429 Out << iName << "_params.push_back(" << opNames[i] << ");";
1432 Out << "CallInst* " << iName << " = CallInst::Create("
1433 << opNames[call->getNumArgOperands()] << ", "
1434 << iName << "_params, \"";
1435 } else if (call->getNumArgOperands() == 1) {
1436 Out << "CallInst* " << iName << " = CallInst::Create("
1437 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
1439 Out << "CallInst* " << iName << " = CallInst::Create("
1440 << opNames[call->getNumArgOperands()] << ", \"";
1442 printEscapedString(call->getName());
1443 Out << "\", " << bbname << ");";
1444 nl(Out) << iName << "->setCallingConv(";
1445 printCallingConv(call->getCallingConv());
1447 nl(Out) << iName << "->setTailCall("
1448 << (call->isTailCall() ? "true" : "false");
1451 printAttributes(call->getAttributes(), iName);
1452 Out << iName << "->setAttributes(" << iName << "_PAL);";
1456 case Instruction::Select: {
1457 const SelectInst* sel = cast<SelectInst>(I);
1458 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1459 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1460 printEscapedString(sel->getName());
1461 Out << "\", " << bbname << ");";
1464 case Instruction::UserOp1:
1466 case Instruction::UserOp2: {
1467 /// FIXME: What should be done here?
1470 case Instruction::VAArg: {
1471 const VAArgInst* va = cast<VAArgInst>(I);
1472 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1473 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1474 printEscapedString(va->getName());
1475 Out << "\", " << bbname << ");";
1478 case Instruction::ExtractElement: {
1479 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1480 Out << "ExtractElementInst* " << getCppName(eei)
1481 << " = new ExtractElementInst(" << opNames[0]
1482 << ", " << opNames[1] << ", \"";
1483 printEscapedString(eei->getName());
1484 Out << "\", " << bbname << ");";
1487 case Instruction::InsertElement: {
1488 const InsertElementInst* iei = cast<InsertElementInst>(I);
1489 Out << "InsertElementInst* " << getCppName(iei)
1490 << " = InsertElementInst::Create(" << opNames[0]
1491 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1492 printEscapedString(iei->getName());
1493 Out << "\", " << bbname << ");";
1496 case Instruction::ShuffleVector: {
1497 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1498 Out << "ShuffleVectorInst* " << getCppName(svi)
1499 << " = new ShuffleVectorInst(" << opNames[0]
1500 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1501 printEscapedString(svi->getName());
1502 Out << "\", " << bbname << ");";
1505 case Instruction::ExtractValue: {
1506 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1507 Out << "std::vector<unsigned> " << iName << "_indices;";
1509 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1510 Out << iName << "_indices.push_back("
1511 << evi->idx_begin()[i] << ");";
1514 Out << "ExtractValueInst* " << getCppName(evi)
1515 << " = ExtractValueInst::Create(" << opNames[0]
1517 << iName << "_indices, \"";
1518 printEscapedString(evi->getName());
1519 Out << "\", " << bbname << ");";
1522 case Instruction::InsertValue: {
1523 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1524 Out << "std::vector<unsigned> " << iName << "_indices;";
1526 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1527 Out << iName << "_indices.push_back("
1528 << ivi->idx_begin()[i] << ");";
1531 Out << "InsertValueInst* " << getCppName(ivi)
1532 << " = InsertValueInst::Create(" << opNames[0]
1533 << ", " << opNames[1] << ", "
1534 << iName << "_indices, \"";
1535 printEscapedString(ivi->getName());
1536 Out << "\", " << bbname << ");";
1539 case Instruction::Fence: {
1540 const FenceInst *fi = cast<FenceInst>(I);
1541 StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1542 StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1543 Out << "FenceInst* " << iName
1544 << " = new FenceInst(mod->getContext(), "
1545 << Ordering << ", " << CrossThread << ", " << bbname
1549 case Instruction::AtomicCmpXchg: {
1550 const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1551 StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1552 StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1553 Out << "AtomicCmpXchgInst* " << iName
1554 << " = new AtomicCmpXchgInst("
1555 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
1556 << Ordering << ", " << CrossThread << ", " << bbname
1558 nl(Out) << iName << "->setName(\"";
1559 printEscapedString(cxi->getName());
1563 case Instruction::AtomicRMW: {
1564 const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1565 StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1566 StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1567 StringRef Operation;
1568 switch (rmwi->getOperation()) {
1569 case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1570 case AtomicRMWInst::Add: Operation = "AtomicRMWInst::Add"; break;
1571 case AtomicRMWInst::Sub: Operation = "AtomicRMWInst::Sub"; break;
1572 case AtomicRMWInst::And: Operation = "AtomicRMWInst::And"; break;
1573 case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1574 case AtomicRMWInst::Or: Operation = "AtomicRMWInst::Or"; break;
1575 case AtomicRMWInst::Xor: Operation = "AtomicRMWInst::Xor"; break;
1576 case AtomicRMWInst::Max: Operation = "AtomicRMWInst::Max"; break;
1577 case AtomicRMWInst::Min: Operation = "AtomicRMWInst::Min"; break;
1578 case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1579 case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1580 case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1582 Out << "AtomicRMWInst* " << iName
1583 << " = new AtomicRMWInst("
1584 << Operation << ", "
1585 << opNames[0] << ", " << opNames[1] << ", "
1586 << Ordering << ", " << CrossThread << ", " << bbname
1588 nl(Out) << iName << "->setName(\"";
1589 printEscapedString(rmwi->getName());
1593 case Instruction::LandingPad: {
1594 const LandingPadInst *lpi = cast<LandingPadInst>(I);
1595 Out << "LandingPadInst* " << iName << " = LandingPadInst::Create(";
1596 printCppName(lpi->getType());
1597 Out << ", " << opNames[0] << ", " << lpi->getNumClauses() << ", \"";
1598 printEscapedString(lpi->getName());
1599 Out << "\", " << bbname << ");";
1600 nl(Out) << iName << "->setCleanup("
1601 << (lpi->isCleanup() ? "true" : "false")
1603 for (unsigned i = 0, e = lpi->getNumClauses(); i != e; ++i)
1604 nl(Out) << iName << "->addClause(" << opNames[i+1] << ");";
1608 DefinedValues.insert(I);
1613 // Print out the types, constants and declarations needed by one function
1614 void CppWriter::printFunctionUses(const Function* F) {
1615 nl(Out) << "// Type Definitions"; nl(Out);
1617 // Print the function's return type
1618 printType(F->getReturnType());
1620 // Print the function's function type
1621 printType(F->getFunctionType());
1623 // Print the types of each of the function's arguments
1624 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1626 printType(AI->getType());
1630 // Print type definitions for every type referenced by an instruction and
1631 // make a note of any global values or constants that are referenced
1632 SmallPtrSet<GlobalValue*,64> gvs;
1633 SmallPtrSet<Constant*,64> consts;
1634 for (Function::const_iterator BB = F->begin(), BE = F->end();
1636 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1638 // Print the type of the instruction itself
1639 printType(I->getType());
1641 // Print the type of each of the instruction's operands
1642 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1643 Value* operand = I->getOperand(i);
1644 printType(operand->getType());
1646 // If the operand references a GVal or Constant, make a note of it
1647 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1649 if (GenerationType != GenFunction)
1650 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1651 if (GVar->hasInitializer())
1652 consts.insert(GVar->getInitializer());
1653 } else if (Constant* C = dyn_cast<Constant>(operand)) {
1655 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1656 // If the operand references a GVal or Constant, make a note of it
1657 Value* operand = C->getOperand(j);
1658 printType(operand->getType());
1659 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1661 if (GenerationType != GenFunction)
1662 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1663 if (GVar->hasInitializer())
1664 consts.insert(GVar->getInitializer());
1672 // Print the function declarations for any functions encountered
1673 nl(Out) << "// Function Declarations"; nl(Out);
1674 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1676 if (Function* Fun = dyn_cast<Function>(*I)) {
1677 if (!is_inline || Fun != F)
1678 printFunctionHead(Fun);
1682 // Print the global variable declarations for any variables encountered
1683 nl(Out) << "// Global Variable Declarations"; nl(Out);
1684 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1686 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1687 printVariableHead(F);
1690 // Print the constants found
1691 nl(Out) << "// Constant Definitions"; nl(Out);
1692 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1693 E = consts.end(); I != E; ++I) {
1697 // Process the global variables definitions now that all the constants have
1698 // been emitted. These definitions just couple the gvars with their constant
1700 if (GenerationType != GenFunction) {
1701 nl(Out) << "// Global Variable Definitions"; nl(Out);
1702 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1704 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1705 printVariableBody(GV);
1710 void CppWriter::printFunctionHead(const Function* F) {
1711 nl(Out) << "Function* " << getCppName(F);
1712 Out << " = mod->getFunction(\"";
1713 printEscapedString(F->getName());
1715 nl(Out) << "if (!" << getCppName(F) << ") {";
1716 nl(Out) << getCppName(F);
1718 Out<< " = Function::Create(";
1719 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1720 nl(Out) << "/*Linkage=*/";
1721 printLinkageType(F->getLinkage());
1723 nl(Out) << "/*Name=*/\"";
1724 printEscapedString(F->getName());
1725 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1728 Out << "->setCallingConv(";
1729 printCallingConv(F->getCallingConv());
1732 if (F->hasSection()) {
1734 Out << "->setSection(\"" << F->getSection() << "\");";
1737 if (F->getAlignment()) {
1739 Out << "->setAlignment(" << F->getAlignment() << ");";
1742 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1744 Out << "->setVisibility(";
1745 printVisibilityType(F->getVisibility());
1751 Out << "->setGC(\"" << F->getGC() << "\");";
1756 printAttributes(F->getAttributes(), getCppName(F));
1758 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1762 void CppWriter::printFunctionBody(const Function *F) {
1763 if (F->isDeclaration())
1764 return; // external functions have no bodies.
1766 // Clear the DefinedValues and ForwardRefs maps because we can't have
1767 // cross-function forward refs
1768 ForwardRefs.clear();
1769 DefinedValues.clear();
1771 // Create all the argument values
1773 if (!F->arg_empty()) {
1774 Out << "Function::arg_iterator args = " << getCppName(F)
1775 << "->arg_begin();";
1778 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1780 Out << "Value* " << getCppName(AI) << " = args++;";
1782 if (AI->hasName()) {
1783 Out << getCppName(AI) << "->setName(\"";
1784 printEscapedString(AI->getName());
1791 // Create all the basic blocks
1793 for (Function::const_iterator BI = F->begin(), BE = F->end();
1795 std::string bbname(getCppName(BI));
1796 Out << "BasicBlock* " << bbname <<
1797 " = BasicBlock::Create(mod->getContext(), \"";
1799 printEscapedString(BI->getName());
1800 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1804 // Output all of its basic blocks... for the function
1805 for (Function::const_iterator BI = F->begin(), BE = F->end();
1807 std::string bbname(getCppName(BI));
1808 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1811 // Output all of the instructions in the basic block...
1812 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1814 printInstruction(I,bbname);
1818 // Loop over the ForwardRefs and resolve them now that all instructions
1820 if (!ForwardRefs.empty()) {
1821 nl(Out) << "// Resolve Forward References";
1825 while (!ForwardRefs.empty()) {
1826 ForwardRefMap::iterator I = ForwardRefs.begin();
1827 Out << I->second << "->replaceAllUsesWith("
1828 << getCppName(I->first) << "); delete " << I->second << ";";
1830 ForwardRefs.erase(I);
1834 void CppWriter::printInline(const std::string& fname,
1835 const std::string& func) {
1836 const Function* F = TheModule->getFunction(func);
1838 error(std::string("Function '") + func + "' not found in input module");
1841 if (F->isDeclaration()) {
1842 error(std::string("Function '") + func + "' is external!");
1845 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1847 unsigned arg_count = 1;
1848 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1850 Out << ", Value* arg_" << arg_count++;
1855 printFunctionUses(F);
1856 printFunctionBody(F);
1858 Out << "return " << getCppName(F->begin()) << ";";
1863 void CppWriter::printModuleBody() {
1864 // Print out all the type definitions
1865 nl(Out) << "// Type Definitions"; nl(Out);
1866 printTypes(TheModule);
1868 // Functions can call each other and global variables can reference them so
1869 // define all the functions first before emitting their function bodies.
1870 nl(Out) << "// Function Declarations"; nl(Out);
1871 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1873 printFunctionHead(I);
1875 // Process the global variables declarations. We can't initialze them until
1876 // after the constants are printed so just print a header for each global
1877 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1878 for (Module::const_global_iterator I = TheModule->global_begin(),
1879 E = TheModule->global_end(); I != E; ++I) {
1880 printVariableHead(I);
1883 // Print out all the constants definitions. Constants don't recurse except
1884 // through GlobalValues. All GlobalValues have been declared at this point
1885 // so we can proceed to generate the constants.
1886 nl(Out) << "// Constant Definitions"; nl(Out);
1887 printConstants(TheModule);
1889 // Process the global variables definitions now that all the constants have
1890 // been emitted. These definitions just couple the gvars with their constant
1892 nl(Out) << "// Global Variable Definitions"; nl(Out);
1893 for (Module::const_global_iterator I = TheModule->global_begin(),
1894 E = TheModule->global_end(); I != E; ++I) {
1895 printVariableBody(I);
1898 // Finally, we can safely put out all of the function bodies.
1899 nl(Out) << "// Function Definitions"; nl(Out);
1900 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1902 if (!I->isDeclaration()) {
1903 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1907 printFunctionBody(I);
1914 void CppWriter::printProgram(const std::string& fname,
1915 const std::string& mName) {
1916 Out << "#include <llvm/Pass.h>\n";
1917 Out << "#include <llvm/PassManager.h>\n";
1919 Out << "#include <llvm/ADT/SmallVector.h>\n";
1920 Out << "#include <llvm/Analysis/Verifier.h>\n";
1921 Out << "#include <llvm/IR/BasicBlock.h>\n";
1922 Out << "#include <llvm/IR/CallingConv.h>\n";
1923 Out << "#include <llvm/IR/Constants.h>\n";
1924 Out << "#include <llvm/IR/DerivedTypes.h>\n";
1925 Out << "#include <llvm/IR/Function.h>\n";
1926 Out << "#include <llvm/IR/GlobalVariable.h>\n";
1927 Out << "#include <llvm/IR/InlineAsm.h>\n";
1928 Out << "#include <llvm/IR/Instructions.h>\n";
1929 Out << "#include <llvm/IR/LLVMContext.h>\n";
1930 Out << "#include <llvm/IR/Module.h>\n";
1931 Out << "#include <llvm/IR/PrintModulePass.h>\n";
1932 Out << "#include <llvm/Support/FormattedStream.h>\n";
1933 Out << "#include <llvm/Support/MathExtras.h>\n";
1934 Out << "#include <algorithm>\n";
1935 Out << "using namespace llvm;\n\n";
1936 Out << "Module* " << fname << "();\n\n";
1937 Out << "int main(int argc, char**argv) {\n";
1938 Out << " Module* Mod = " << fname << "();\n";
1939 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1940 Out << " PassManager PM;\n";
1941 Out << " PM.add(createPrintModulePass(&outs()));\n";
1942 Out << " PM.run(*Mod);\n";
1943 Out << " return 0;\n";
1945 printModule(fname,mName);
1948 void CppWriter::printModule(const std::string& fname,
1949 const std::string& mName) {
1950 nl(Out) << "Module* " << fname << "() {";
1951 nl(Out,1) << "// Module Construction";
1952 nl(Out) << "Module* mod = new Module(\"";
1953 printEscapedString(mName);
1954 Out << "\", getGlobalContext());";
1955 if (!TheModule->getTargetTriple().empty()) {
1956 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1958 if (!TheModule->getTargetTriple().empty()) {
1959 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1963 if (!TheModule->getModuleInlineAsm().empty()) {
1964 nl(Out) << "mod->setModuleInlineAsm(\"";
1965 printEscapedString(TheModule->getModuleInlineAsm());
1971 nl(Out) << "return mod;";
1976 void CppWriter::printContents(const std::string& fname,
1977 const std::string& mName) {
1978 Out << "\nModule* " << fname << "(Module *mod) {\n";
1979 Out << "\nmod->setModuleIdentifier(\"";
1980 printEscapedString(mName);
1983 Out << "\nreturn mod;\n";
1987 void CppWriter::printFunction(const std::string& fname,
1988 const std::string& funcName) {
1989 const Function* F = TheModule->getFunction(funcName);
1991 error(std::string("Function '") + funcName + "' not found in input module");
1994 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1995 printFunctionUses(F);
1996 printFunctionHead(F);
1997 printFunctionBody(F);
1998 Out << "return " << getCppName(F) << ";\n";
2002 void CppWriter::printFunctions() {
2003 const Module::FunctionListType &funcs = TheModule->getFunctionList();
2004 Module::const_iterator I = funcs.begin();
2005 Module::const_iterator IE = funcs.end();
2007 for (; I != IE; ++I) {
2008 const Function &func = *I;
2009 if (!func.isDeclaration()) {
2010 std::string name("define_");
2011 name += func.getName();
2012 printFunction(name, func.getName());
2017 void CppWriter::printVariable(const std::string& fname,
2018 const std::string& varName) {
2019 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
2022 error(std::string("Variable '") + varName + "' not found in input module");
2025 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
2026 printVariableUses(GV);
2027 printVariableHead(GV);
2028 printVariableBody(GV);
2029 Out << "return " << getCppName(GV) << ";\n";
2033 void CppWriter::printType(const std::string &fname,
2034 const std::string &typeName) {
2035 Type* Ty = TheModule->getTypeByName(typeName);
2037 error(std::string("Type '") + typeName + "' not found in input module");
2040 Out << "\nType* " << fname << "(Module *mod) {\n";
2042 Out << "return " << getCppName(Ty) << ";\n";
2046 bool CppWriter::runOnModule(Module &M) {
2050 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2052 // Get the name of the function we're supposed to generate
2053 std::string fname = FuncName.getValue();
2055 // Get the name of the thing we are to generate
2056 std::string tgtname = NameToGenerate.getValue();
2057 if (GenerationType == GenModule ||
2058 GenerationType == GenContents ||
2059 GenerationType == GenProgram ||
2060 GenerationType == GenFunctions) {
2061 if (tgtname == "!bad!") {
2062 if (M.getModuleIdentifier() == "-")
2063 tgtname = "<stdin>";
2065 tgtname = M.getModuleIdentifier();
2067 } else if (tgtname == "!bad!")
2068 error("You must use the -for option with -gen-{function,variable,type}");
2070 switch (WhatToGenerate(GenerationType)) {
2073 fname = "makeLLVMModule";
2074 printProgram(fname,tgtname);
2078 fname = "makeLLVMModule";
2079 printModule(fname,tgtname);
2083 fname = "makeLLVMModuleContents";
2084 printContents(fname,tgtname);
2088 fname = "makeLLVMFunction";
2089 printFunction(fname,tgtname);
2096 fname = "makeLLVMInline";
2097 printInline(fname,tgtname);
2101 fname = "makeLLVMVariable";
2102 printVariable(fname,tgtname);
2106 fname = "makeLLVMType";
2107 printType(fname,tgtname);
2114 char CppWriter::ID = 0;
2116 //===----------------------------------------------------------------------===//
2117 // External Interface declaration
2118 //===----------------------------------------------------------------------===//
2120 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2121 formatted_raw_ostream &o,
2122 CodeGenFileType FileType,
2124 AnalysisID StartAfter,
2125 AnalysisID StopAfter) {
2126 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
2127 PM.add(new CppWriter(o));