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/ADT/STLExtras.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/IR/CallingConv.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/InlineAsm.h"
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/LegacyPassManager.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/TargetRegistry.h"
43 static cl::opt<std::string>
44 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
45 cl::value_desc("function name"));
58 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
59 cl::desc("Choose what kind of output to generate"),
62 clEnumValN(GenProgram, "program", "Generate a complete program"),
63 clEnumValN(GenModule, "module", "Generate a module definition"),
64 clEnumValN(GenContents, "contents", "Generate contents of a module"),
65 clEnumValN(GenFunction, "function", "Generate a function definition"),
66 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
67 clEnumValN(GenInline, "inline", "Generate an inline function"),
68 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
69 clEnumValN(GenType, "type", "Generate a type definition"),
74 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
75 cl::desc("Specify the name of the thing to generate"),
78 extern "C" void LLVMInitializeCppBackendTarget() {
79 // Register the target.
80 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
84 typedef std::vector<Type*> TypeList;
85 typedef std::map<Type*,std::string> TypeMap;
86 typedef std::map<const Value*,std::string> ValueMap;
87 typedef std::set<std::string> NameSet;
88 typedef std::set<Type*> TypeSet;
89 typedef std::set<const Value*> ValueSet;
90 typedef std::map<const Value*,std::string> ForwardRefMap;
92 /// CppWriter - This class is the main chunk of code that converts an LLVM
93 /// module to a C++ translation unit.
94 class CppWriter : public ModulePass {
95 std::unique_ptr<formatted_raw_ostream> OutOwner;
96 formatted_raw_ostream &Out;
97 const Module *TheModule;
102 TypeSet DefinedTypes;
103 ValueSet DefinedValues;
104 ForwardRefMap ForwardRefs;
106 unsigned indent_level;
110 explicit CppWriter(std::unique_ptr<formatted_raw_ostream> o)
111 : ModulePass(ID), OutOwner(std::move(o)), Out(*OutOwner), uniqueNum(0),
112 is_inline(false), indent_level(0) {}
114 const char *getPassName() const override { return "C++ backend"; }
116 bool runOnModule(Module &M) override;
118 void printProgram(const std::string& fname, const std::string& modName );
119 void printModule(const std::string& fname, const std::string& modName );
120 void printContents(const std::string& fname, const std::string& modName );
121 void printFunction(const std::string& fname, const std::string& funcName );
122 void printFunctions();
123 void printInline(const std::string& fname, const std::string& funcName );
124 void printVariable(const std::string& fname, const std::string& varName );
125 void printType(const std::string& fname, const std::string& typeName );
127 void error(const std::string& msg);
130 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
131 inline void in() { indent_level++; }
132 inline void out() { if (indent_level >0) indent_level--; }
135 void printLinkageType(GlobalValue::LinkageTypes LT);
136 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
137 void printDLLStorageClassType(GlobalValue::DLLStorageClassTypes DSCType);
138 void printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM);
139 void printCallingConv(CallingConv::ID cc);
140 void printEscapedString(const std::string& str);
141 void printCFP(const ConstantFP* CFP);
143 std::string getCppName(Type* val);
144 inline void printCppName(Type* val);
146 std::string getCppName(const Value* val);
147 inline void printCppName(const Value* val);
149 void printAttributes(const AttributeSet &PAL, const std::string &name);
150 void printType(Type* Ty);
151 void printTypes(const Module* M);
153 void printConstant(const Constant *CPV);
154 void printConstants(const Module* M);
156 void printVariableUses(const GlobalVariable *GV);
157 void printVariableHead(const GlobalVariable *GV);
158 void printVariableBody(const GlobalVariable *GV);
160 void printFunctionUses(const Function *F);
161 void printFunctionHead(const Function *F);
162 void printFunctionBody(const Function *F);
163 void printInstruction(const Instruction *I, const std::string& bbname);
164 std::string getOpName(const Value*);
166 void printModuleBody();
168 } // end anonymous namespace.
170 formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
172 if (delta >= 0 || indent_level >= unsigned(-delta))
173 indent_level += delta;
174 Out.indent(indent_level);
178 static inline void sanitize(std::string &str) {
179 for (size_t i = 0; i < str.length(); ++i)
180 if (!isalnum(str[i]) && str[i] != '_')
184 static std::string getTypePrefix(Type *Ty) {
185 switch (Ty->getTypeID()) {
186 case Type::VoidTyID: return "void_";
187 case Type::IntegerTyID:
188 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
189 case Type::FloatTyID: return "float_";
190 case Type::DoubleTyID: return "double_";
191 case Type::LabelTyID: return "label_";
192 case Type::FunctionTyID: return "func_";
193 case Type::StructTyID: return "struct_";
194 case Type::ArrayTyID: return "array_";
195 case Type::PointerTyID: return "ptr_";
196 case Type::VectorTyID: return "packed_";
197 default: return "other_";
201 void CppWriter::error(const std::string& msg) {
202 report_fatal_error(msg);
205 static inline std::string ftostr(const APFloat& V) {
207 if (&V.getSemantics() == &APFloat::IEEEdouble) {
208 raw_string_ostream(Buf) << V.convertToDouble();
210 } else if (&V.getSemantics() == &APFloat::IEEEsingle) {
211 raw_string_ostream(Buf) << (double)V.convertToFloat();
214 return "<unknown format in ftostr>"; // error
217 // printCFP - Print a floating point constant .. very carefully :)
218 // This makes sure that conversion to/from floating yields the same binary
219 // result so that we don't lose precision.
220 void CppWriter::printCFP(const ConstantFP *CFP) {
222 APFloat APF = APFloat(CFP->getValueAPF()); // copy
223 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
224 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
225 Out << "ConstantFP::get(mod->getContext(), ";
229 sprintf(Buffer, "%A", APF.convertToDouble());
230 if ((!strncmp(Buffer, "0x", 2) ||
231 !strncmp(Buffer, "-0x", 3) ||
232 !strncmp(Buffer, "+0x", 3)) &&
233 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
234 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
235 Out << "BitsToDouble(" << Buffer << ")";
237 Out << "BitsToFloat((float)" << Buffer << ")";
241 std::string StrVal = ftostr(CFP->getValueAPF());
243 while (StrVal[0] == ' ')
244 StrVal.erase(StrVal.begin());
246 // Check to make sure that the stringized number is not some string like
247 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
248 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
249 ((StrVal[0] == '-' || StrVal[0] == '+') &&
250 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
251 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
252 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
255 Out << StrVal << "f";
256 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
257 Out << "BitsToDouble(0x"
258 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
259 << "ULL) /* " << StrVal << " */";
261 Out << "BitsToFloat(0x"
262 << utohexstr((uint32_t)CFP->getValueAPF().
263 bitcastToAPInt().getZExtValue())
264 << "U) /* " << StrVal << " */";
272 void CppWriter::printCallingConv(CallingConv::ID cc){
273 // Print the calling convention.
275 case CallingConv::C: Out << "CallingConv::C"; break;
276 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
277 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
278 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
279 default: Out << cc; break;
283 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
285 case GlobalValue::InternalLinkage:
286 Out << "GlobalValue::InternalLinkage"; break;
287 case GlobalValue::PrivateLinkage:
288 Out << "GlobalValue::PrivateLinkage"; 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::ExternalWeakLinkage:
304 Out << "GlobalValue::ExternalWeakLinkage"; break;
305 case GlobalValue::CommonLinkage:
306 Out << "GlobalValue::CommonLinkage"; break;
310 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
312 case GlobalValue::DefaultVisibility:
313 Out << "GlobalValue::DefaultVisibility";
315 case GlobalValue::HiddenVisibility:
316 Out << "GlobalValue::HiddenVisibility";
318 case GlobalValue::ProtectedVisibility:
319 Out << "GlobalValue::ProtectedVisibility";
324 void CppWriter::printDLLStorageClassType(
325 GlobalValue::DLLStorageClassTypes DSCType) {
327 case GlobalValue::DefaultStorageClass:
328 Out << "GlobalValue::DefaultStorageClass";
330 case GlobalValue::DLLImportStorageClass:
331 Out << "GlobalValue::DLLImportStorageClass";
333 case GlobalValue::DLLExportStorageClass:
334 Out << "GlobalValue::DLLExportStorageClass";
339 void CppWriter::printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM) {
341 case GlobalVariable::NotThreadLocal:
342 Out << "GlobalVariable::NotThreadLocal";
344 case GlobalVariable::GeneralDynamicTLSModel:
345 Out << "GlobalVariable::GeneralDynamicTLSModel";
347 case GlobalVariable::LocalDynamicTLSModel:
348 Out << "GlobalVariable::LocalDynamicTLSModel";
350 case GlobalVariable::InitialExecTLSModel:
351 Out << "GlobalVariable::InitialExecTLSModel";
353 case GlobalVariable::LocalExecTLSModel:
354 Out << "GlobalVariable::LocalExecTLSModel";
359 // printEscapedString - Print each character of the specified string, escaping
360 // it if it is not printable or if it is an escape char.
361 void CppWriter::printEscapedString(const std::string &Str) {
362 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
363 unsigned char C = Str[i];
364 if (isprint(C) && C != '"' && C != '\\') {
368 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
369 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
374 std::string CppWriter::getCppName(Type* Ty) {
375 switch (Ty->getTypeID()) {
379 return "Type::getVoidTy(mod->getContext())";
380 case Type::IntegerTyID: {
381 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
382 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
384 case Type::X86_FP80TyID:
385 return "Type::getX86_FP80Ty(mod->getContext())";
386 case Type::FloatTyID:
387 return "Type::getFloatTy(mod->getContext())";
388 case Type::DoubleTyID:
389 return "Type::getDoubleTy(mod->getContext())";
390 case Type::LabelTyID:
391 return "Type::getLabelTy(mod->getContext())";
392 case Type::X86_MMXTyID:
393 return "Type::getX86_MMXTy(mod->getContext())";
396 // Now, see if we've seen the type before and return that
397 TypeMap::iterator I = TypeNames.find(Ty);
398 if (I != TypeNames.end())
401 // Okay, let's build a new name for this type. Start with a prefix
402 const char* prefix = nullptr;
403 switch (Ty->getTypeID()) {
404 case Type::FunctionTyID: prefix = "FuncTy_"; break;
405 case Type::StructTyID: prefix = "StructTy_"; break;
406 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
407 case Type::PointerTyID: prefix = "PointerTy_"; break;
408 case Type::VectorTyID: prefix = "VectorTy_"; break;
409 default: prefix = "OtherTy_"; break; // prevent breakage
412 // See if the type has a name in the symboltable and build accordingly
414 if (StructType *STy = dyn_cast<StructType>(Ty))
416 name = STy->getName();
419 name = utostr(uniqueNum++);
421 name = std::string(prefix) + name;
425 return TypeNames[Ty] = name;
428 void CppWriter::printCppName(Type* Ty) {
429 printEscapedString(getCppName(Ty));
432 std::string CppWriter::getCppName(const Value* val) {
434 ValueMap::iterator I = ValueNames.find(val);
435 if (I != ValueNames.end() && I->first == val)
438 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
439 name = std::string("gvar_") +
440 getTypePrefix(GV->getType()->getElementType());
441 } else if (isa<Function>(val)) {
442 name = std::string("func_");
443 } else if (const Constant* C = dyn_cast<Constant>(val)) {
444 name = std::string("const_") + getTypePrefix(C->getType());
445 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
447 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
448 Function::const_arg_iterator(Arg)) + 1;
449 name = std::string("arg_") + utostr(argNum);
450 NameSet::iterator NI = UsedNames.find(name);
451 if (NI != UsedNames.end())
452 name += std::string("_") + utostr(uniqueNum++);
453 UsedNames.insert(name);
454 return ValueNames[val] = name;
456 name = getTypePrefix(val->getType());
459 name = getTypePrefix(val->getType());
462 name += val->getName();
464 name += utostr(uniqueNum++);
466 NameSet::iterator NI = UsedNames.find(name);
467 if (NI != UsedNames.end())
468 name += std::string("_") + utostr(uniqueNum++);
469 UsedNames.insert(name);
470 return ValueNames[val] = name;
473 void CppWriter::printCppName(const Value* val) {
474 printEscapedString(getCppName(val));
477 void CppWriter::printAttributes(const AttributeSet &PAL,
478 const std::string &name) {
479 Out << "AttributeSet " << name << "_PAL;";
481 if (!PAL.isEmpty()) {
482 Out << '{'; in(); nl(Out);
483 Out << "SmallVector<AttributeSet, 4> Attrs;"; nl(Out);
484 Out << "AttributeSet PAS;"; in(); nl(Out);
485 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
486 unsigned index = PAL.getSlotIndex(i);
487 AttrBuilder attrs(PAL.getSlotAttributes(i), index);
488 Out << "{"; in(); nl(Out);
489 Out << "AttrBuilder B;"; nl(Out);
491 #define HANDLE_ATTR(X) \
492 if (attrs.contains(Attribute::X)) { \
493 Out << "B.addAttribute(Attribute::" #X ");"; nl(Out); \
494 attrs.removeAttribute(Attribute::X); \
499 HANDLE_ATTR(NoReturn);
501 HANDLE_ATTR(StructRet);
502 HANDLE_ATTR(NoUnwind);
503 HANDLE_ATTR(NoAlias);
505 HANDLE_ATTR(InAlloca);
507 HANDLE_ATTR(ReadNone);
508 HANDLE_ATTR(ReadOnly);
509 HANDLE_ATTR(NoInline);
510 HANDLE_ATTR(AlwaysInline);
511 HANDLE_ATTR(OptimizeNone);
512 HANDLE_ATTR(OptimizeForSize);
513 HANDLE_ATTR(StackProtect);
514 HANDLE_ATTR(StackProtectReq);
515 HANDLE_ATTR(StackProtectStrong);
516 HANDLE_ATTR(SafeStack);
517 HANDLE_ATTR(NoCapture);
518 HANDLE_ATTR(NoRedZone);
519 HANDLE_ATTR(NoImplicitFloat);
521 HANDLE_ATTR(InlineHint);
522 HANDLE_ATTR(ReturnsTwice);
523 HANDLE_ATTR(UWTable);
524 HANDLE_ATTR(NonLazyBind);
525 HANDLE_ATTR(MinSize);
528 if (attrs.contains(Attribute::StackAlignment)) {
529 Out << "B.addStackAlignmentAttr(" << attrs.getStackAlignment()<<')';
531 attrs.removeAttribute(Attribute::StackAlignment);
534 Out << "PAS = AttributeSet::get(mod->getContext(), ";
538 Out << index << "U,";
539 Out << " B);"; out(); nl(Out);
540 Out << "}"; out(); nl(Out);
542 Out << "Attrs.push_back(PAS);"; nl(Out);
544 Out << name << "_PAL = AttributeSet::get(mod->getContext(), Attrs);";
551 void CppWriter::printType(Type* Ty) {
552 // We don't print definitions for primitive types
553 if (Ty->isFloatingPointTy() || Ty->isX86_MMXTy() || Ty->isIntegerTy() ||
554 Ty->isLabelTy() || Ty->isMetadataTy() || Ty->isVoidTy())
557 // If we already defined this type, we don't need to define it again.
558 if (DefinedTypes.find(Ty) != DefinedTypes.end())
561 // Everything below needs the name for the type so get it now.
562 std::string typeName(getCppName(Ty));
564 // Print the type definition
565 switch (Ty->getTypeID()) {
566 case Type::FunctionTyID: {
567 FunctionType* FT = cast<FunctionType>(Ty);
568 Out << "std::vector<Type*>" << typeName << "_args;";
570 FunctionType::param_iterator PI = FT->param_begin();
571 FunctionType::param_iterator PE = FT->param_end();
572 for (; PI != PE; ++PI) {
573 Type* argTy = static_cast<Type*>(*PI);
575 std::string argName(getCppName(argTy));
576 Out << typeName << "_args.push_back(" << argName;
580 printType(FT->getReturnType());
581 std::string retTypeName(getCppName(FT->getReturnType()));
582 Out << "FunctionType* " << typeName << " = FunctionType::get(";
583 in(); nl(Out) << "/*Result=*/" << retTypeName;
585 nl(Out) << "/*Params=*/" << typeName << "_args,";
586 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
591 case Type::StructTyID: {
592 StructType* ST = cast<StructType>(Ty);
593 if (!ST->isLiteral()) {
594 Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
595 printEscapedString(ST->getName());
598 Out << "if (!" << typeName << ") {";
600 Out << typeName << " = ";
601 Out << "StructType::create(mod->getContext(), \"";
602 printEscapedString(ST->getName());
607 // Indicate that this type is now defined.
608 DefinedTypes.insert(Ty);
611 Out << "std::vector<Type*>" << typeName << "_fields;";
613 StructType::element_iterator EI = ST->element_begin();
614 StructType::element_iterator EE = ST->element_end();
615 for (; EI != EE; ++EI) {
616 Type* fieldTy = static_cast<Type*>(*EI);
618 std::string fieldName(getCppName(fieldTy));
619 Out << typeName << "_fields.push_back(" << fieldName;
624 if (ST->isLiteral()) {
625 Out << "StructType *" << typeName << " = ";
626 Out << "StructType::get(" << "mod->getContext(), ";
628 Out << "if (" << typeName << "->isOpaque()) {";
630 Out << typeName << "->setBody(";
633 Out << typeName << "_fields, /*isPacked=*/"
634 << (ST->isPacked() ? "true" : "false") << ");";
636 if (!ST->isLiteral()) {
642 case Type::ArrayTyID: {
643 ArrayType* AT = cast<ArrayType>(Ty);
644 Type* ET = AT->getElementType();
646 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
647 std::string elemName(getCppName(ET));
648 Out << "ArrayType* " << typeName << " = ArrayType::get("
649 << elemName << ", " << AT->getNumElements() << ");";
654 case Type::PointerTyID: {
655 PointerType* PT = cast<PointerType>(Ty);
656 Type* ET = PT->getElementType();
658 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
659 std::string elemName(getCppName(ET));
660 Out << "PointerType* " << typeName << " = PointerType::get("
661 << elemName << ", " << PT->getAddressSpace() << ");";
666 case Type::VectorTyID: {
667 VectorType* PT = cast<VectorType>(Ty);
668 Type* ET = PT->getElementType();
670 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
671 std::string elemName(getCppName(ET));
672 Out << "VectorType* " << typeName << " = VectorType::get("
673 << elemName << ", " << PT->getNumElements() << ");";
679 error("Invalid TypeID");
682 // Indicate that this type is now defined.
683 DefinedTypes.insert(Ty);
685 // Finally, separate the type definition from other with a newline.
689 void CppWriter::printTypes(const Module* M) {
690 // Add all of the global variables to the value table.
691 for (Module::const_global_iterator I = TheModule->global_begin(),
692 E = TheModule->global_end(); I != E; ++I) {
693 if (I->hasInitializer())
694 printType(I->getInitializer()->getType());
695 printType(I->getType());
698 // Add all the functions to the table
699 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
701 printType(FI->getReturnType());
702 printType(FI->getFunctionType());
703 // Add all the function arguments
704 for (Function::const_arg_iterator AI = FI->arg_begin(),
705 AE = FI->arg_end(); AI != AE; ++AI) {
706 printType(AI->getType());
709 // Add all of the basic blocks and instructions
710 for (Function::const_iterator BB = FI->begin(),
711 E = FI->end(); BB != E; ++BB) {
712 printType(BB->getType());
713 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
715 printType(I->getType());
716 for (unsigned i = 0; i < I->getNumOperands(); ++i)
717 printType(I->getOperand(i)->getType());
724 // printConstant - Print out a constant pool entry...
725 void CppWriter::printConstant(const Constant *CV) {
726 // First, if the constant is actually a GlobalValue (variable or function)
727 // or its already in the constant list then we've printed it already and we
729 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
732 std::string constName(getCppName(CV));
733 std::string typeName(getCppName(CV->getType()));
735 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
736 std::string constValue = CI->getValue().toString(10, true);
737 Out << "ConstantInt* " << constName
738 << " = ConstantInt::get(mod->getContext(), APInt("
739 << cast<IntegerType>(CI->getType())->getBitWidth()
740 << ", StringRef(\"" << constValue << "\"), 10));";
741 } else if (isa<ConstantAggregateZero>(CV)) {
742 Out << "ConstantAggregateZero* " << constName
743 << " = ConstantAggregateZero::get(" << typeName << ");";
744 } else if (isa<ConstantPointerNull>(CV)) {
745 Out << "ConstantPointerNull* " << constName
746 << " = ConstantPointerNull::get(" << typeName << ");";
747 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
748 Out << "ConstantFP* " << constName << " = ";
751 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
752 Out << "std::vector<Constant*> " << constName << "_elems;";
754 unsigned N = CA->getNumOperands();
755 for (unsigned i = 0; i < N; ++i) {
756 printConstant(CA->getOperand(i)); // recurse to print operands
757 Out << constName << "_elems.push_back("
758 << getCppName(CA->getOperand(i)) << ");";
761 Out << "Constant* " << constName << " = ConstantArray::get("
762 << typeName << ", " << constName << "_elems);";
763 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
764 Out << "std::vector<Constant*> " << constName << "_fields;";
766 unsigned N = CS->getNumOperands();
767 for (unsigned i = 0; i < N; i++) {
768 printConstant(CS->getOperand(i));
769 Out << constName << "_fields.push_back("
770 << getCppName(CS->getOperand(i)) << ");";
773 Out << "Constant* " << constName << " = ConstantStruct::get("
774 << typeName << ", " << constName << "_fields);";
775 } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
776 Out << "std::vector<Constant*> " << constName << "_elems;";
778 unsigned N = CVec->getNumOperands();
779 for (unsigned i = 0; i < N; ++i) {
780 printConstant(CVec->getOperand(i));
781 Out << constName << "_elems.push_back("
782 << getCppName(CVec->getOperand(i)) << ");";
785 Out << "Constant* " << constName << " = ConstantVector::get("
786 << typeName << ", " << constName << "_elems);";
787 } else if (isa<UndefValue>(CV)) {
788 Out << "UndefValue* " << constName << " = UndefValue::get("
790 } else if (const ConstantDataSequential *CDS =
791 dyn_cast<ConstantDataSequential>(CV)) {
792 if (CDS->isString()) {
793 Out << "Constant *" << constName <<
794 " = ConstantDataArray::getString(mod->getContext(), \"";
795 StringRef Str = CDS->getAsString();
796 bool nullTerminate = false;
797 if (Str.back() == 0) {
798 Str = Str.drop_back();
799 nullTerminate = true;
801 printEscapedString(Str);
802 // Determine if we want null termination or not.
806 Out << "\", false);";// No null terminator
808 // TODO: Could generate more efficient code generating CDS calls instead.
809 Out << "std::vector<Constant*> " << constName << "_elems;";
811 for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
812 Constant *Elt = CDS->getElementAsConstant(i);
814 Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
817 Out << "Constant* " << constName;
819 if (isa<ArrayType>(CDS->getType()))
820 Out << " = ConstantArray::get(";
822 Out << " = ConstantVector::get(";
823 Out << typeName << ", " << constName << "_elems);";
825 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
826 if (CE->getOpcode() == Instruction::GetElementPtr) {
827 Out << "std::vector<Constant*> " << constName << "_indices;";
829 printConstant(CE->getOperand(0));
830 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
831 printConstant(CE->getOperand(i));
832 Out << constName << "_indices.push_back("
833 << getCppName(CE->getOperand(i)) << ");";
836 Out << "Constant* " << constName
837 << " = ConstantExpr::getGetElementPtr("
838 << getCppName(CE->getOperand(0)) << ", "
839 << constName << "_indices);";
840 } else if (CE->isCast()) {
841 printConstant(CE->getOperand(0));
842 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
843 switch (CE->getOpcode()) {
844 default: llvm_unreachable("Invalid cast opcode");
845 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
846 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
847 case Instruction::SExt: Out << "Instruction::SExt"; break;
848 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
849 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
850 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
851 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
852 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
853 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
854 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
855 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
856 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
858 Out << ", " << getCppName(CE->getOperand(0)) << ", "
859 << getCppName(CE->getType()) << ");";
861 unsigned N = CE->getNumOperands();
862 for (unsigned i = 0; i < N; ++i ) {
863 printConstant(CE->getOperand(i));
865 Out << "Constant* " << constName << " = ConstantExpr::";
866 switch (CE->getOpcode()) {
867 case Instruction::Add: Out << "getAdd("; break;
868 case Instruction::FAdd: Out << "getFAdd("; break;
869 case Instruction::Sub: Out << "getSub("; break;
870 case Instruction::FSub: Out << "getFSub("; break;
871 case Instruction::Mul: Out << "getMul("; break;
872 case Instruction::FMul: Out << "getFMul("; break;
873 case Instruction::UDiv: Out << "getUDiv("; break;
874 case Instruction::SDiv: Out << "getSDiv("; break;
875 case Instruction::FDiv: Out << "getFDiv("; break;
876 case Instruction::URem: Out << "getURem("; break;
877 case Instruction::SRem: Out << "getSRem("; break;
878 case Instruction::FRem: Out << "getFRem("; break;
879 case Instruction::And: Out << "getAnd("; break;
880 case Instruction::Or: Out << "getOr("; break;
881 case Instruction::Xor: Out << "getXor("; break;
882 case Instruction::ICmp:
883 Out << "getICmp(ICmpInst::ICMP_";
884 switch (CE->getPredicate()) {
885 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
886 case ICmpInst::ICMP_NE: Out << "NE"; break;
887 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
888 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
889 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
890 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
891 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
892 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
893 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
894 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
895 default: error("Invalid ICmp Predicate");
898 case Instruction::FCmp:
899 Out << "getFCmp(FCmpInst::FCMP_";
900 switch (CE->getPredicate()) {
901 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
902 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
903 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
904 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
905 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
906 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
907 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
908 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
909 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
910 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
911 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
912 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
913 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
914 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
915 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
916 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
917 default: error("Invalid FCmp Predicate");
920 case Instruction::Shl: Out << "getShl("; break;
921 case Instruction::LShr: Out << "getLShr("; break;
922 case Instruction::AShr: Out << "getAShr("; break;
923 case Instruction::Select: Out << "getSelect("; break;
924 case Instruction::ExtractElement: Out << "getExtractElement("; break;
925 case Instruction::InsertElement: Out << "getInsertElement("; break;
926 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
928 error("Invalid constant expression");
931 Out << getCppName(CE->getOperand(0));
932 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
933 Out << ", " << getCppName(CE->getOperand(i));
936 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
937 Out << "Constant* " << constName << " = ";
938 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
940 error("Bad Constant");
941 Out << "Constant* " << constName << " = 0; ";
946 void CppWriter::printConstants(const Module* M) {
947 // Traverse all the global variables looking for constant initializers
948 for (Module::const_global_iterator I = TheModule->global_begin(),
949 E = TheModule->global_end(); I != E; ++I)
950 if (I->hasInitializer())
951 printConstant(I->getInitializer());
953 // Traverse the LLVM functions looking for constants
954 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
956 // Add all of the basic blocks and instructions
957 for (Function::const_iterator BB = FI->begin(),
958 E = FI->end(); BB != E; ++BB) {
959 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
961 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
962 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
971 void CppWriter::printVariableUses(const GlobalVariable *GV) {
972 nl(Out) << "// Type Definitions";
974 printType(GV->getType());
975 if (GV->hasInitializer()) {
976 const Constant *Init = GV->getInitializer();
977 printType(Init->getType());
978 if (const Function *F = dyn_cast<Function>(Init)) {
979 nl(Out)<< "/ Function Declarations"; nl(Out);
980 printFunctionHead(F);
981 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
982 nl(Out) << "// Global Variable Declarations"; nl(Out);
983 printVariableHead(gv);
985 nl(Out) << "// Global Variable Definitions"; nl(Out);
986 printVariableBody(gv);
988 nl(Out) << "// Constant Definitions"; nl(Out);
994 void CppWriter::printVariableHead(const GlobalVariable *GV) {
995 nl(Out) << "GlobalVariable* " << getCppName(GV);
997 Out << " = mod->getGlobalVariable(mod->getContext(), ";
998 printEscapedString(GV->getName());
999 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
1000 nl(Out) << "if (!" << getCppName(GV) << ") {";
1001 in(); nl(Out) << getCppName(GV);
1003 Out << " = new GlobalVariable(/*Module=*/*mod, ";
1004 nl(Out) << "/*Type=*/";
1005 printCppName(GV->getType()->getElementType());
1007 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1009 nl(Out) << "/*Linkage=*/";
1010 printLinkageType(GV->getLinkage());
1012 nl(Out) << "/*Initializer=*/0, ";
1013 if (GV->hasInitializer()) {
1014 Out << "// has initializer, specified below";
1016 nl(Out) << "/*Name=*/\"";
1017 printEscapedString(GV->getName());
1021 if (GV->hasSection()) {
1023 Out << "->setSection(\"";
1024 printEscapedString(GV->getSection());
1028 if (GV->getAlignment()) {
1030 Out << "->setAlignment(" << GV->getAlignment() << ");";
1033 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1035 Out << "->setVisibility(";
1036 printVisibilityType(GV->getVisibility());
1040 if (GV->getDLLStorageClass() != GlobalValue::DefaultStorageClass) {
1042 Out << "->setDLLStorageClass(";
1043 printDLLStorageClassType(GV->getDLLStorageClass());
1047 if (GV->isThreadLocal()) {
1049 Out << "->setThreadLocalMode(";
1050 printThreadLocalMode(GV->getThreadLocalMode());
1055 out(); Out << "}"; nl(Out);
1059 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1060 if (GV->hasInitializer()) {
1062 Out << "->setInitializer(";
1063 Out << getCppName(GV->getInitializer()) << ");";
1068 std::string CppWriter::getOpName(const Value* V) {
1069 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1070 return getCppName(V);
1072 // See if its alread in the map of forward references, if so just return the
1073 // name we already set up for it
1074 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1075 if (I != ForwardRefs.end())
1078 // This is a new forward reference. Generate a unique name for it
1079 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1081 // Yes, this is a hack. An Argument is the smallest instantiable value that
1082 // we can make as a placeholder for the real value. We'll replace these
1083 // Argument instances later.
1084 Out << "Argument* " << result << " = new Argument("
1085 << getCppName(V->getType()) << ");";
1087 ForwardRefs[V] = result;
1091 static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1093 case NotAtomic: return "NotAtomic";
1094 case Unordered: return "Unordered";
1095 case Monotonic: return "Monotonic";
1096 case Acquire: return "Acquire";
1097 case Release: return "Release";
1098 case AcquireRelease: return "AcquireRelease";
1099 case SequentiallyConsistent: return "SequentiallyConsistent";
1101 llvm_unreachable("Unknown ordering");
1104 static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1105 switch (SynchScope) {
1106 case SingleThread: return "SingleThread";
1107 case CrossThread: return "CrossThread";
1109 llvm_unreachable("Unknown synch scope");
1112 // printInstruction - This member is called for each Instruction in a function.
1113 void CppWriter::printInstruction(const Instruction *I,
1114 const std::string& bbname) {
1115 std::string iName(getCppName(I));
1117 // Before we emit this instruction, we need to take care of generating any
1118 // forward references. So, we get the names of all the operands in advance
1119 const unsigned Ops(I->getNumOperands());
1120 std::string* opNames = new std::string[Ops];
1121 for (unsigned i = 0; i < Ops; i++)
1122 opNames[i] = getOpName(I->getOperand(i));
1124 switch (I->getOpcode()) {
1126 error("Invalid instruction");
1129 case Instruction::Ret: {
1130 const ReturnInst* ret = cast<ReturnInst>(I);
1131 Out << "ReturnInst::Create(mod->getContext(), "
1132 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1135 case Instruction::Br: {
1136 const BranchInst* br = cast<BranchInst>(I);
1137 Out << "BranchInst::Create(" ;
1138 if (br->getNumOperands() == 3) {
1139 Out << opNames[2] << ", "
1140 << opNames[1] << ", "
1141 << opNames[0] << ", ";
1143 } else if (br->getNumOperands() == 1) {
1144 Out << opNames[0] << ", ";
1146 error("Branch with 2 operands?");
1148 Out << bbname << ");";
1151 case Instruction::Switch: {
1152 const SwitchInst *SI = cast<SwitchInst>(I);
1153 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1154 << getOpName(SI->getCondition()) << ", "
1155 << getOpName(SI->getDefaultDest()) << ", "
1156 << SI->getNumCases() << ", " << bbname << ");";
1158 for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
1160 const ConstantInt* CaseVal = i.getCaseValue();
1161 const BasicBlock *BB = i.getCaseSuccessor();
1162 Out << iName << "->addCase("
1163 << getOpName(CaseVal) << ", "
1164 << getOpName(BB) << ");";
1169 case Instruction::IndirectBr: {
1170 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1171 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1172 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1174 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1175 Out << iName << "->addDestination(" << opNames[i] << ");";
1180 case Instruction::Resume: {
1181 Out << "ResumeInst::Create(" << opNames[0] << ", " << bbname << ");";
1184 case Instruction::Invoke: {
1185 const InvokeInst* inv = cast<InvokeInst>(I);
1186 Out << "std::vector<Value*> " << iName << "_params;";
1188 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1189 Out << iName << "_params.push_back("
1190 << getOpName(inv->getArgOperand(i)) << ");";
1193 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1194 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1195 << getOpName(inv->getCalledValue()) << ", "
1196 << getOpName(inv->getNormalDest()) << ", "
1197 << getOpName(inv->getUnwindDest()) << ", "
1198 << iName << "_params, \"";
1199 printEscapedString(inv->getName());
1200 Out << "\", " << bbname << ");";
1201 nl(Out) << iName << "->setCallingConv(";
1202 printCallingConv(inv->getCallingConv());
1204 printAttributes(inv->getAttributes(), iName);
1205 Out << iName << "->setAttributes(" << iName << "_PAL);";
1209 case Instruction::Unreachable: {
1210 Out << "new UnreachableInst("
1211 << "mod->getContext(), "
1215 case Instruction::Add:
1216 case Instruction::FAdd:
1217 case Instruction::Sub:
1218 case Instruction::FSub:
1219 case Instruction::Mul:
1220 case Instruction::FMul:
1221 case Instruction::UDiv:
1222 case Instruction::SDiv:
1223 case Instruction::FDiv:
1224 case Instruction::URem:
1225 case Instruction::SRem:
1226 case Instruction::FRem:
1227 case Instruction::And:
1228 case Instruction::Or:
1229 case Instruction::Xor:
1230 case Instruction::Shl:
1231 case Instruction::LShr:
1232 case Instruction::AShr:{
1233 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1234 switch (I->getOpcode()) {
1235 case Instruction::Add: Out << "Instruction::Add"; break;
1236 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1237 case Instruction::Sub: Out << "Instruction::Sub"; break;
1238 case Instruction::FSub: Out << "Instruction::FSub"; break;
1239 case Instruction::Mul: Out << "Instruction::Mul"; break;
1240 case Instruction::FMul: Out << "Instruction::FMul"; break;
1241 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1242 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1243 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1244 case Instruction::URem:Out << "Instruction::URem"; break;
1245 case Instruction::SRem:Out << "Instruction::SRem"; break;
1246 case Instruction::FRem:Out << "Instruction::FRem"; break;
1247 case Instruction::And: Out << "Instruction::And"; break;
1248 case Instruction::Or: Out << "Instruction::Or"; break;
1249 case Instruction::Xor: Out << "Instruction::Xor"; break;
1250 case Instruction::Shl: Out << "Instruction::Shl"; break;
1251 case Instruction::LShr:Out << "Instruction::LShr"; break;
1252 case Instruction::AShr:Out << "Instruction::AShr"; break;
1253 default: Out << "Instruction::BadOpCode"; break;
1255 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1256 printEscapedString(I->getName());
1257 Out << "\", " << bbname << ");";
1260 case Instruction::FCmp: {
1261 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1262 switch (cast<FCmpInst>(I)->getPredicate()) {
1263 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1264 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1265 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1266 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1267 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1268 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1269 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1270 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1271 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1272 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1273 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1274 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1275 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1276 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1277 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1278 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1279 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1281 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1282 printEscapedString(I->getName());
1286 case Instruction::ICmp: {
1287 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1288 switch (cast<ICmpInst>(I)->getPredicate()) {
1289 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1290 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1291 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1292 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1293 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1294 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1295 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1296 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1297 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1298 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1299 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1301 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1302 printEscapedString(I->getName());
1306 case Instruction::Alloca: {
1307 const AllocaInst* allocaI = cast<AllocaInst>(I);
1308 Out << "AllocaInst* " << iName << " = new AllocaInst("
1309 << getCppName(allocaI->getAllocatedType()) << ", ";
1310 if (allocaI->isArrayAllocation())
1311 Out << opNames[0] << ", ";
1313 printEscapedString(allocaI->getName());
1314 Out << "\", " << bbname << ");";
1315 if (allocaI->getAlignment())
1316 nl(Out) << iName << "->setAlignment("
1317 << allocaI->getAlignment() << ");";
1320 case Instruction::Load: {
1321 const LoadInst* load = cast<LoadInst>(I);
1322 Out << "LoadInst* " << iName << " = new LoadInst("
1323 << opNames[0] << ", \"";
1324 printEscapedString(load->getName());
1325 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1326 << ", " << bbname << ");";
1327 if (load->getAlignment())
1328 nl(Out) << iName << "->setAlignment("
1329 << load->getAlignment() << ");";
1330 if (load->isAtomic()) {
1331 StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1332 StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1333 nl(Out) << iName << "->setAtomic("
1334 << Ordering << ", " << CrossThread << ");";
1338 case Instruction::Store: {
1339 const StoreInst* store = cast<StoreInst>(I);
1340 Out << "StoreInst* " << iName << " = new StoreInst("
1341 << opNames[0] << ", "
1342 << opNames[1] << ", "
1343 << (store->isVolatile() ? "true" : "false")
1344 << ", " << bbname << ");";
1345 if (store->getAlignment())
1346 nl(Out) << iName << "->setAlignment("
1347 << store->getAlignment() << ");";
1348 if (store->isAtomic()) {
1349 StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1350 StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1351 nl(Out) << iName << "->setAtomic("
1352 << Ordering << ", " << CrossThread << ");";
1356 case Instruction::GetElementPtr: {
1357 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1358 if (gep->getNumOperands() <= 2) {
1359 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1361 if (gep->getNumOperands() == 2)
1362 Out << ", " << opNames[1];
1364 Out << "std::vector<Value*> " << iName << "_indices;";
1366 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1367 Out << iName << "_indices.push_back("
1368 << opNames[i] << ");";
1371 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1372 << opNames[0] << ", " << iName << "_indices";
1375 printEscapedString(gep->getName());
1376 Out << "\", " << bbname << ");";
1379 case Instruction::PHI: {
1380 const PHINode* phi = cast<PHINode>(I);
1382 Out << "PHINode* " << iName << " = PHINode::Create("
1383 << getCppName(phi->getType()) << ", "
1384 << phi->getNumIncomingValues() << ", \"";
1385 printEscapedString(phi->getName());
1386 Out << "\", " << bbname << ");";
1388 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
1389 Out << iName << "->addIncoming("
1390 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
1391 << getOpName(phi->getIncomingBlock(i)) << ");";
1396 case Instruction::Trunc:
1397 case Instruction::ZExt:
1398 case Instruction::SExt:
1399 case Instruction::FPTrunc:
1400 case Instruction::FPExt:
1401 case Instruction::FPToUI:
1402 case Instruction::FPToSI:
1403 case Instruction::UIToFP:
1404 case Instruction::SIToFP:
1405 case Instruction::PtrToInt:
1406 case Instruction::IntToPtr:
1407 case Instruction::BitCast: {
1408 const CastInst* cst = cast<CastInst>(I);
1409 Out << "CastInst* " << iName << " = new ";
1410 switch (I->getOpcode()) {
1411 case Instruction::Trunc: Out << "TruncInst"; break;
1412 case Instruction::ZExt: Out << "ZExtInst"; break;
1413 case Instruction::SExt: Out << "SExtInst"; break;
1414 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1415 case Instruction::FPExt: Out << "FPExtInst"; break;
1416 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1417 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1418 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1419 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1420 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1421 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1422 case Instruction::BitCast: Out << "BitCastInst"; break;
1423 default: llvm_unreachable("Unreachable");
1425 Out << "(" << opNames[0] << ", "
1426 << getCppName(cst->getType()) << ", \"";
1427 printEscapedString(cst->getName());
1428 Out << "\", " << bbname << ");";
1431 case Instruction::Call: {
1432 const CallInst* call = cast<CallInst>(I);
1433 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1434 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1435 << getCppName(ila->getFunctionType()) << ", \""
1436 << ila->getAsmString() << "\", \""
1437 << ila->getConstraintString() << "\","
1438 << (ila->hasSideEffects() ? "true" : "false") << ");";
1441 if (call->getNumArgOperands() > 1) {
1442 Out << "std::vector<Value*> " << iName << "_params;";
1444 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
1445 Out << iName << "_params.push_back(" << opNames[i] << ");";
1448 Out << "CallInst* " << iName << " = CallInst::Create("
1449 << opNames[call->getNumArgOperands()] << ", "
1450 << iName << "_params, \"";
1451 } else if (call->getNumArgOperands() == 1) {
1452 Out << "CallInst* " << iName << " = CallInst::Create("
1453 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
1455 Out << "CallInst* " << iName << " = CallInst::Create("
1456 << opNames[call->getNumArgOperands()] << ", \"";
1458 printEscapedString(call->getName());
1459 Out << "\", " << bbname << ");";
1460 nl(Out) << iName << "->setCallingConv(";
1461 printCallingConv(call->getCallingConv());
1463 nl(Out) << iName << "->setTailCall("
1464 << (call->isTailCall() ? "true" : "false");
1467 printAttributes(call->getAttributes(), iName);
1468 Out << iName << "->setAttributes(" << iName << "_PAL);";
1472 case Instruction::Select: {
1473 const SelectInst* sel = cast<SelectInst>(I);
1474 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1475 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1476 printEscapedString(sel->getName());
1477 Out << "\", " << bbname << ");";
1480 case Instruction::UserOp1:
1482 case Instruction::UserOp2: {
1483 /// FIXME: What should be done here?
1486 case Instruction::VAArg: {
1487 const VAArgInst* va = cast<VAArgInst>(I);
1488 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1489 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1490 printEscapedString(va->getName());
1491 Out << "\", " << bbname << ");";
1494 case Instruction::ExtractElement: {
1495 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1496 Out << "ExtractElementInst* " << getCppName(eei)
1497 << " = new ExtractElementInst(" << opNames[0]
1498 << ", " << opNames[1] << ", \"";
1499 printEscapedString(eei->getName());
1500 Out << "\", " << bbname << ");";
1503 case Instruction::InsertElement: {
1504 const InsertElementInst* iei = cast<InsertElementInst>(I);
1505 Out << "InsertElementInst* " << getCppName(iei)
1506 << " = InsertElementInst::Create(" << opNames[0]
1507 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1508 printEscapedString(iei->getName());
1509 Out << "\", " << bbname << ");";
1512 case Instruction::ShuffleVector: {
1513 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1514 Out << "ShuffleVectorInst* " << getCppName(svi)
1515 << " = new ShuffleVectorInst(" << opNames[0]
1516 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1517 printEscapedString(svi->getName());
1518 Out << "\", " << bbname << ");";
1521 case Instruction::ExtractValue: {
1522 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1523 Out << "std::vector<unsigned> " << iName << "_indices;";
1525 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1526 Out << iName << "_indices.push_back("
1527 << evi->idx_begin()[i] << ");";
1530 Out << "ExtractValueInst* " << getCppName(evi)
1531 << " = ExtractValueInst::Create(" << opNames[0]
1533 << iName << "_indices, \"";
1534 printEscapedString(evi->getName());
1535 Out << "\", " << bbname << ");";
1538 case Instruction::InsertValue: {
1539 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1540 Out << "std::vector<unsigned> " << iName << "_indices;";
1542 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1543 Out << iName << "_indices.push_back("
1544 << ivi->idx_begin()[i] << ");";
1547 Out << "InsertValueInst* " << getCppName(ivi)
1548 << " = InsertValueInst::Create(" << opNames[0]
1549 << ", " << opNames[1] << ", "
1550 << iName << "_indices, \"";
1551 printEscapedString(ivi->getName());
1552 Out << "\", " << bbname << ");";
1555 case Instruction::Fence: {
1556 const FenceInst *fi = cast<FenceInst>(I);
1557 StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1558 StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1559 Out << "FenceInst* " << iName
1560 << " = new FenceInst(mod->getContext(), "
1561 << Ordering << ", " << CrossThread << ", " << bbname
1565 case Instruction::AtomicCmpXchg: {
1566 const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1567 StringRef SuccessOrdering =
1568 ConvertAtomicOrdering(cxi->getSuccessOrdering());
1569 StringRef FailureOrdering =
1570 ConvertAtomicOrdering(cxi->getFailureOrdering());
1571 StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1572 Out << "AtomicCmpXchgInst* " << iName
1573 << " = new AtomicCmpXchgInst("
1574 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
1575 << SuccessOrdering << ", " << FailureOrdering << ", "
1576 << CrossThread << ", " << bbname
1578 nl(Out) << iName << "->setName(\"";
1579 printEscapedString(cxi->getName());
1581 nl(Out) << iName << "->setVolatile("
1582 << (cxi->isVolatile() ? "true" : "false") << ");";
1583 nl(Out) << iName << "->setWeak("
1584 << (cxi->isWeak() ? "true" : "false") << ");";
1587 case Instruction::AtomicRMW: {
1588 const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1589 StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1590 StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1591 StringRef Operation;
1592 switch (rmwi->getOperation()) {
1593 case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1594 case AtomicRMWInst::Add: Operation = "AtomicRMWInst::Add"; break;
1595 case AtomicRMWInst::Sub: Operation = "AtomicRMWInst::Sub"; break;
1596 case AtomicRMWInst::And: Operation = "AtomicRMWInst::And"; break;
1597 case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1598 case AtomicRMWInst::Or: Operation = "AtomicRMWInst::Or"; break;
1599 case AtomicRMWInst::Xor: Operation = "AtomicRMWInst::Xor"; break;
1600 case AtomicRMWInst::Max: Operation = "AtomicRMWInst::Max"; break;
1601 case AtomicRMWInst::Min: Operation = "AtomicRMWInst::Min"; break;
1602 case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1603 case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1604 case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1606 Out << "AtomicRMWInst* " << iName
1607 << " = new AtomicRMWInst("
1608 << Operation << ", "
1609 << opNames[0] << ", " << opNames[1] << ", "
1610 << Ordering << ", " << CrossThread << ", " << bbname
1612 nl(Out) << iName << "->setName(\"";
1613 printEscapedString(rmwi->getName());
1615 nl(Out) << iName << "->setVolatile("
1616 << (rmwi->isVolatile() ? "true" : "false") << ");";
1619 case Instruction::LandingPad: {
1620 const LandingPadInst *lpi = cast<LandingPadInst>(I);
1621 Out << "LandingPadInst* " << iName << " = LandingPadInst::Create(";
1622 printCppName(lpi->getType());
1623 Out << ", " << opNames[0] << ", " << lpi->getNumClauses() << ", \"";
1624 printEscapedString(lpi->getName());
1625 Out << "\", " << bbname << ");";
1626 nl(Out) << iName << "->setCleanup("
1627 << (lpi->isCleanup() ? "true" : "false")
1629 for (unsigned i = 0, e = lpi->getNumClauses(); i != e; ++i)
1630 nl(Out) << iName << "->addClause(" << opNames[i+1] << ");";
1634 DefinedValues.insert(I);
1639 // Print out the types, constants and declarations needed by one function
1640 void CppWriter::printFunctionUses(const Function* F) {
1641 nl(Out) << "// Type Definitions"; nl(Out);
1643 // Print the function's return type
1644 printType(F->getReturnType());
1646 // Print the function's function type
1647 printType(F->getFunctionType());
1649 // Print the types of each of the function's arguments
1650 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1652 printType(AI->getType());
1656 // Print type definitions for every type referenced by an instruction and
1657 // make a note of any global values or constants that are referenced
1658 SmallPtrSet<GlobalValue*,64> gvs;
1659 SmallPtrSet<Constant*,64> consts;
1660 for (Function::const_iterator BB = F->begin(), BE = F->end();
1662 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1664 // Print the type of the instruction itself
1665 printType(I->getType());
1667 // Print the type of each of the instruction's operands
1668 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1669 Value* operand = I->getOperand(i);
1670 printType(operand->getType());
1672 // If the operand references a GVal or Constant, make a note of it
1673 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1675 if (GenerationType != GenFunction)
1676 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1677 if (GVar->hasInitializer())
1678 consts.insert(GVar->getInitializer());
1679 } else if (Constant* C = dyn_cast<Constant>(operand)) {
1681 for (Value* operand : C->operands()) {
1682 // If the operand references a GVal or Constant, make a note of it
1683 printType(operand->getType());
1684 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1686 if (GenerationType != GenFunction)
1687 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1688 if (GVar->hasInitializer())
1689 consts.insert(GVar->getInitializer());
1697 // Print the function declarations for any functions encountered
1698 nl(Out) << "// Function Declarations"; nl(Out);
1699 for (auto *GV : gvs) {
1700 if (Function *Fun = dyn_cast<Function>(GV)) {
1701 if (!is_inline || Fun != F)
1702 printFunctionHead(Fun);
1706 // Print the global variable declarations for any variables encountered
1707 nl(Out) << "// Global Variable Declarations"; nl(Out);
1708 for (auto *GV : gvs) {
1709 if (GlobalVariable *F = dyn_cast<GlobalVariable>(GV))
1710 printVariableHead(F);
1713 // Print the constants found
1714 nl(Out) << "// Constant Definitions"; nl(Out);
1715 for (const auto *C : consts) {
1719 // Process the global variables definitions now that all the constants have
1720 // been emitted. These definitions just couple the gvars with their constant
1722 if (GenerationType != GenFunction) {
1723 nl(Out) << "// Global Variable Definitions"; nl(Out);
1724 for (auto *GV : gvs) {
1725 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(GV))
1726 printVariableBody(Var);
1731 void CppWriter::printFunctionHead(const Function* F) {
1732 nl(Out) << "Function* " << getCppName(F);
1733 Out << " = mod->getFunction(\"";
1734 printEscapedString(F->getName());
1736 nl(Out) << "if (!" << getCppName(F) << ") {";
1737 nl(Out) << getCppName(F);
1739 Out<< " = Function::Create(";
1740 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1741 nl(Out) << "/*Linkage=*/";
1742 printLinkageType(F->getLinkage());
1744 nl(Out) << "/*Name=*/\"";
1745 printEscapedString(F->getName());
1746 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1749 Out << "->setCallingConv(";
1750 printCallingConv(F->getCallingConv());
1753 if (F->hasSection()) {
1755 Out << "->setSection(\"" << F->getSection() << "\");";
1758 if (F->getAlignment()) {
1760 Out << "->setAlignment(" << F->getAlignment() << ");";
1763 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1765 Out << "->setVisibility(";
1766 printVisibilityType(F->getVisibility());
1770 if (F->getDLLStorageClass() != GlobalValue::DefaultStorageClass) {
1772 Out << "->setDLLStorageClass(";
1773 printDLLStorageClassType(F->getDLLStorageClass());
1779 Out << "->setGC(\"" << F->getGC() << "\");";
1784 printAttributes(F->getAttributes(), getCppName(F));
1786 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1790 void CppWriter::printFunctionBody(const Function *F) {
1791 if (F->isDeclaration())
1792 return; // external functions have no bodies.
1794 // Clear the DefinedValues and ForwardRefs maps because we can't have
1795 // cross-function forward refs
1796 ForwardRefs.clear();
1797 DefinedValues.clear();
1799 // Create all the argument values
1801 if (!F->arg_empty()) {
1802 Out << "Function::arg_iterator args = " << getCppName(F)
1803 << "->arg_begin();";
1806 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1808 Out << "Value* " << getCppName(AI) << " = args++;";
1810 if (AI->hasName()) {
1811 Out << getCppName(AI) << "->setName(\"";
1812 printEscapedString(AI->getName());
1819 // Create all the basic blocks
1821 for (Function::const_iterator BI = F->begin(), BE = F->end();
1823 std::string bbname(getCppName(BI));
1824 Out << "BasicBlock* " << bbname <<
1825 " = BasicBlock::Create(mod->getContext(), \"";
1827 printEscapedString(BI->getName());
1828 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1832 // Output all of its basic blocks... for the function
1833 for (Function::const_iterator BI = F->begin(), BE = F->end();
1835 std::string bbname(getCppName(BI));
1836 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1839 // Output all of the instructions in the basic block...
1840 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1842 printInstruction(I,bbname);
1846 // Loop over the ForwardRefs and resolve them now that all instructions
1848 if (!ForwardRefs.empty()) {
1849 nl(Out) << "// Resolve Forward References";
1853 while (!ForwardRefs.empty()) {
1854 ForwardRefMap::iterator I = ForwardRefs.begin();
1855 Out << I->second << "->replaceAllUsesWith("
1856 << getCppName(I->first) << "); delete " << I->second << ";";
1858 ForwardRefs.erase(I);
1862 void CppWriter::printInline(const std::string& fname,
1863 const std::string& func) {
1864 const Function* F = TheModule->getFunction(func);
1866 error(std::string("Function '") + func + "' not found in input module");
1869 if (F->isDeclaration()) {
1870 error(std::string("Function '") + func + "' is external!");
1873 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1875 unsigned arg_count = 1;
1876 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1878 Out << ", Value* arg_" << arg_count++;
1883 printFunctionUses(F);
1884 printFunctionBody(F);
1886 Out << "return " << getCppName(F->begin()) << ";";
1891 void CppWriter::printModuleBody() {
1892 // Print out all the type definitions
1893 nl(Out) << "// Type Definitions"; nl(Out);
1894 printTypes(TheModule);
1896 // Functions can call each other and global variables can reference them so
1897 // define all the functions first before emitting their function bodies.
1898 nl(Out) << "// Function Declarations"; nl(Out);
1899 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1901 printFunctionHead(I);
1903 // Process the global variables declarations. We can't initialze them until
1904 // after the constants are printed so just print a header for each global
1905 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1906 for (Module::const_global_iterator I = TheModule->global_begin(),
1907 E = TheModule->global_end(); I != E; ++I) {
1908 printVariableHead(I);
1911 // Print out all the constants definitions. Constants don't recurse except
1912 // through GlobalValues. All GlobalValues have been declared at this point
1913 // so we can proceed to generate the constants.
1914 nl(Out) << "// Constant Definitions"; nl(Out);
1915 printConstants(TheModule);
1917 // Process the global variables definitions now that all the constants have
1918 // been emitted. These definitions just couple the gvars with their constant
1920 nl(Out) << "// Global Variable Definitions"; nl(Out);
1921 for (Module::const_global_iterator I = TheModule->global_begin(),
1922 E = TheModule->global_end(); I != E; ++I) {
1923 printVariableBody(I);
1926 // Finally, we can safely put out all of the function bodies.
1927 nl(Out) << "// Function Definitions"; nl(Out);
1928 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1930 if (!I->isDeclaration()) {
1931 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1935 printFunctionBody(I);
1942 void CppWriter::printProgram(const std::string& fname,
1943 const std::string& mName) {
1944 Out << "#include <llvm/Pass.h>\n";
1946 Out << "#include <llvm/ADT/SmallVector.h>\n";
1947 Out << "#include <llvm/Analysis/Verifier.h>\n";
1948 Out << "#include <llvm/IR/BasicBlock.h>\n";
1949 Out << "#include <llvm/IR/CallingConv.h>\n";
1950 Out << "#include <llvm/IR/Constants.h>\n";
1951 Out << "#include <llvm/IR/DerivedTypes.h>\n";
1952 Out << "#include <llvm/IR/Function.h>\n";
1953 Out << "#include <llvm/IR/GlobalVariable.h>\n";
1954 Out << "#include <llvm/IR/IRPrintingPasses.h>\n";
1955 Out << "#include <llvm/IR/InlineAsm.h>\n";
1956 Out << "#include <llvm/IR/Instructions.h>\n";
1957 Out << "#include <llvm/IR/LLVMContext.h>\n";
1958 Out << "#include <llvm/IR/LegacyPassManager.h>\n";
1959 Out << "#include <llvm/IR/Module.h>\n";
1960 Out << "#include <llvm/Support/FormattedStream.h>\n";
1961 Out << "#include <llvm/Support/MathExtras.h>\n";
1962 Out << "#include <algorithm>\n";
1963 Out << "using namespace llvm;\n\n";
1964 Out << "Module* " << fname << "();\n\n";
1965 Out << "int main(int argc, char**argv) {\n";
1966 Out << " Module* Mod = " << fname << "();\n";
1967 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1968 Out << " PassManager PM;\n";
1969 Out << " PM.add(createPrintModulePass(&outs()));\n";
1970 Out << " PM.run(*Mod);\n";
1971 Out << " return 0;\n";
1973 printModule(fname,mName);
1976 void CppWriter::printModule(const std::string& fname,
1977 const std::string& mName) {
1978 nl(Out) << "Module* " << fname << "() {";
1979 nl(Out,1) << "// Module Construction";
1980 nl(Out) << "Module* mod = new Module(\"";
1981 printEscapedString(mName);
1982 Out << "\", getGlobalContext());";
1983 if (!TheModule->getTargetTriple().empty()) {
1984 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayoutStr()
1987 if (!TheModule->getTargetTriple().empty()) {
1988 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1992 if (!TheModule->getModuleInlineAsm().empty()) {
1993 nl(Out) << "mod->setModuleInlineAsm(\"";
1994 printEscapedString(TheModule->getModuleInlineAsm());
2000 nl(Out) << "return mod;";
2005 void CppWriter::printContents(const std::string& fname,
2006 const std::string& mName) {
2007 Out << "\nModule* " << fname << "(Module *mod) {\n";
2008 Out << "\nmod->setModuleIdentifier(\"";
2009 printEscapedString(mName);
2012 Out << "\nreturn mod;\n";
2016 void CppWriter::printFunction(const std::string& fname,
2017 const std::string& funcName) {
2018 const Function* F = TheModule->getFunction(funcName);
2020 error(std::string("Function '") + funcName + "' not found in input module");
2023 Out << "\nFunction* " << fname << "(Module *mod) {\n";
2024 printFunctionUses(F);
2025 printFunctionHead(F);
2026 printFunctionBody(F);
2027 Out << "return " << getCppName(F) << ";\n";
2031 void CppWriter::printFunctions() {
2032 const Module::FunctionListType &funcs = TheModule->getFunctionList();
2033 Module::const_iterator I = funcs.begin();
2034 Module::const_iterator IE = funcs.end();
2036 for (; I != IE; ++I) {
2037 const Function &func = *I;
2038 if (!func.isDeclaration()) {
2039 std::string name("define_");
2040 name += func.getName();
2041 printFunction(name, func.getName());
2046 void CppWriter::printVariable(const std::string& fname,
2047 const std::string& varName) {
2048 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
2051 error(std::string("Variable '") + varName + "' not found in input module");
2054 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
2055 printVariableUses(GV);
2056 printVariableHead(GV);
2057 printVariableBody(GV);
2058 Out << "return " << getCppName(GV) << ";\n";
2062 void CppWriter::printType(const std::string &fname,
2063 const std::string &typeName) {
2064 Type* Ty = TheModule->getTypeByName(typeName);
2066 error(std::string("Type '") + typeName + "' not found in input module");
2069 Out << "\nType* " << fname << "(Module *mod) {\n";
2071 Out << "return " << getCppName(Ty) << ";\n";
2075 bool CppWriter::runOnModule(Module &M) {
2079 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2081 // Get the name of the function we're supposed to generate
2082 std::string fname = FuncName.getValue();
2084 // Get the name of the thing we are to generate
2085 std::string tgtname = NameToGenerate.getValue();
2086 if (GenerationType == GenModule ||
2087 GenerationType == GenContents ||
2088 GenerationType == GenProgram ||
2089 GenerationType == GenFunctions) {
2090 if (tgtname == "!bad!") {
2091 if (M.getModuleIdentifier() == "-")
2092 tgtname = "<stdin>";
2094 tgtname = M.getModuleIdentifier();
2096 } else if (tgtname == "!bad!")
2097 error("You must use the -for option with -gen-{function,variable,type}");
2099 switch (WhatToGenerate(GenerationType)) {
2102 fname = "makeLLVMModule";
2103 printProgram(fname,tgtname);
2107 fname = "makeLLVMModule";
2108 printModule(fname,tgtname);
2112 fname = "makeLLVMModuleContents";
2113 printContents(fname,tgtname);
2117 fname = "makeLLVMFunction";
2118 printFunction(fname,tgtname);
2125 fname = "makeLLVMInline";
2126 printInline(fname,tgtname);
2130 fname = "makeLLVMVariable";
2131 printVariable(fname,tgtname);
2135 fname = "makeLLVMType";
2136 printType(fname,tgtname);
2143 char CppWriter::ID = 0;
2145 //===----------------------------------------------------------------------===//
2146 // External Interface declaration
2147 //===----------------------------------------------------------------------===//
2149 bool CPPTargetMachine::addPassesToEmitFile(
2150 PassManagerBase &PM, raw_pwrite_stream &o, CodeGenFileType FileType,
2151 bool DisableVerify, AnalysisID StartAfter, AnalysisID StopAfter,
2152 MachineFunctionInitializer *MFInitializer) {
2153 if (FileType != TargetMachine::CGFT_AssemblyFile)
2155 auto FOut = llvm::make_unique<formatted_raw_ostream>(o);
2156 PM.add(new CppWriter(std::move(FOut)));