blob: 98ec22c75b8a36d231c4a653f105232e496f2d4b [file] [log] [blame]
Anton Korobeynikov50276522008-04-23 22:29:24 +00001//===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CPPTargetMachine.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instruction.h"
21#include "llvm/Instructions.h"
22#include "llvm/Module.h"
23#include "llvm/Pass.h"
24#include "llvm/PassManager.h"
Evan Cheng1abf2cb2011-07-14 23:50:31 +000025#include "llvm/MC/MCAsmInfo.h"
Evan Cheng59ee62d2011-07-11 03:57:24 +000026#include "llvm/MC/MCInstrInfo.h"
Evan Chengffc0e732011-07-09 05:47:46 +000027#include "llvm/MC/MCSubtargetInfo.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000028#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/Support/CommandLine.h"
Torok Edwin30464702009-07-08 20:55:50 +000030#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000031#include "llvm/Support/FormattedStream.h"
Daniel Dunbar0c795d62009-07-25 06:49:55 +000032#include "llvm/Target/TargetRegistry.h"
Chris Lattner23132b12009-08-24 03:52:50 +000033#include "llvm/ADT/StringExtras.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000034#include "llvm/Config/config.h"
35#include <algorithm>
Anton Korobeynikov50276522008-04-23 22:29:24 +000036#include <set>
Chris Lattner1afcace2011-07-09 17:41:24 +000037#include <map>
Anton Korobeynikov50276522008-04-23 22:29:24 +000038using namespace llvm;
39
40static cl::opt<std::string>
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000041FuncName("cppfname", cl::desc("Specify the name of the generated function"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000042 cl::value_desc("function name"));
43
44enum WhatToGenerate {
45 GenProgram,
46 GenModule,
47 GenContents,
48 GenFunction,
49 GenFunctions,
50 GenInline,
51 GenVariable,
52 GenType
53};
54
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000055static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000056 cl::desc("Choose what kind of output to generate"),
57 cl::init(GenProgram),
58 cl::values(
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000059 clEnumValN(GenProgram, "program", "Generate a complete program"),
60 clEnumValN(GenModule, "module", "Generate a module definition"),
61 clEnumValN(GenContents, "contents", "Generate contents of a module"),
62 clEnumValN(GenFunction, "function", "Generate a function definition"),
63 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
64 clEnumValN(GenInline, "inline", "Generate an inline function"),
65 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
66 clEnumValN(GenType, "type", "Generate a type definition"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000067 clEnumValEnd
68 )
69);
70
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000071static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000072 cl::desc("Specify the name of the thing to generate"),
73 cl::init("!bad!"));
74
Daniel Dunbar0c795d62009-07-25 06:49:55 +000075extern "C" void LLVMInitializeCppBackendTarget() {
76 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000077 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000078}
Douglas Gregor1555a232009-06-16 20:12:29 +000079
Evan Cheng1abf2cb2011-07-14 23:50:31 +000080extern "C" void LLVMInitializeCppBackendMCAsmInfo() {}
81
Evan Cheng0e6a0522011-07-18 20:57:22 +000082extern "C" void LLVMInitializeCppBackendMCRegisterInfo() {}
Evan Cheng59ee62d2011-07-11 03:57:24 +000083
Evan Cheng0e6a0522011-07-18 20:57:22 +000084extern "C" void LLVMInitializeCppBackendMCInstrInfo() {}
85
86extern "C" void LLVMInitializeCppBackendMCSubtargetInfo() {}
Evan Chengffc0e732011-07-09 05:47:46 +000087
Dan Gohman844731a2008-05-13 00:00:25 +000088namespace {
Chris Lattnerdb125cf2011-07-18 04:54:35 +000089 typedef std::vector<Type*> TypeList;
90 typedef std::map<Type*,std::string> TypeMap;
Anton Korobeynikov50276522008-04-23 22:29:24 +000091 typedef std::map<const Value*,std::string> ValueMap;
92 typedef std::set<std::string> NameSet;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000093 typedef std::set<Type*> TypeSet;
Anton Korobeynikov50276522008-04-23 22:29:24 +000094 typedef std::set<const Value*> ValueSet;
95 typedef std::map<const Value*,std::string> ForwardRefMap;
96
97 /// CppWriter - This class is the main chunk of code that converts an LLVM
98 /// module to a C++ translation unit.
99 class CppWriter : public ModulePass {
David Greene71847812009-07-14 20:18:05 +0000100 formatted_raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000101 const Module *TheModule;
102 uint64_t uniqueNum;
103 TypeMap TypeNames;
104 ValueMap ValueNames;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000105 NameSet UsedNames;
106 TypeSet DefinedTypes;
107 ValueSet DefinedValues;
108 ForwardRefMap ForwardRefs;
109 bool is_inline;
Chris Lattner1018c242010-06-21 23:14:47 +0000110 unsigned indent_level;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000111
112 public:
113 static char ID;
David Greene71847812009-07-14 20:18:05 +0000114 explicit CppWriter(formatted_raw_ostream &o) :
Owen Anderson90c579d2010-08-06 18:33:48 +0000115 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000116
117 virtual const char *getPassName() const { return "C++ backend"; }
118
119 bool runOnModule(Module &M);
120
Anton Korobeynikov50276522008-04-23 22:29:24 +0000121 void printProgram(const std::string& fname, const std::string& modName );
122 void printModule(const std::string& fname, const std::string& modName );
123 void printContents(const std::string& fname, const std::string& modName );
124 void printFunction(const std::string& fname, const std::string& funcName );
125 void printFunctions();
126 void printInline(const std::string& fname, const std::string& funcName );
127 void printVariable(const std::string& fname, const std::string& varName );
128 void printType(const std::string& fname, const std::string& typeName );
129
130 void error(const std::string& msg);
131
Chris Lattner1018c242010-06-21 23:14:47 +0000132
133 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
134 inline void in() { indent_level++; }
135 inline void out() { if (indent_level >0) indent_level--; }
136
Anton Korobeynikov50276522008-04-23 22:29:24 +0000137 private:
138 void printLinkageType(GlobalValue::LinkageTypes LT);
139 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000140 void printCallingConv(CallingConv::ID cc);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000141 void printEscapedString(const std::string& str);
142 void printCFP(const ConstantFP* CFP);
143
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000144 std::string getCppName(Type* val);
145 inline void printCppName(Type* val);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000146
147 std::string getCppName(const Value* val);
148 inline void printCppName(const Value* val);
149
Devang Patel05988662008-09-25 21:00:45 +0000150 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000151 void printType(Type* Ty);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000152 void printTypes(const Module* M);
153
154 void printConstant(const Constant *CPV);
155 void printConstants(const Module* M);
156
157 void printVariableUses(const GlobalVariable *GV);
158 void printVariableHead(const GlobalVariable *GV);
159 void printVariableBody(const GlobalVariable *GV);
160
161 void printFunctionUses(const Function *F);
162 void printFunctionHead(const Function *F);
163 void printFunctionBody(const Function *F);
164 void printInstruction(const Instruction *I, const std::string& bbname);
165 std::string getOpName(Value*);
166
167 void printModuleBody();
168 };
Chris Lattner7e6d7452010-06-21 23:12:56 +0000169} // end anonymous namespace.
Anton Korobeynikov50276522008-04-23 22:29:24 +0000170
Chris Lattner1018c242010-06-21 23:14:47 +0000171formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
172 Out << '\n';
Chris Lattner7e6d7452010-06-21 23:12:56 +0000173 if (delta >= 0 || indent_level >= unsigned(-delta))
174 indent_level += delta;
Chris Lattner1018c242010-06-21 23:14:47 +0000175 Out.indent(indent_level);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000176 return Out;
177}
178
Chris Lattner7e6d7452010-06-21 23:12:56 +0000179static inline void sanitize(std::string &str) {
180 for (size_t i = 0; i < str.length(); ++i)
181 if (!isalnum(str[i]) && str[i] != '_')
182 str[i] = '_';
183}
184
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000185static std::string getTypePrefix(Type *Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000186 switch (Ty->getTypeID()) {
187 case Type::VoidTyID: return "void_";
188 case Type::IntegerTyID:
189 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
190 case Type::FloatTyID: return "float_";
191 case Type::DoubleTyID: return "double_";
192 case Type::LabelTyID: return "label_";
193 case Type::FunctionTyID: return "func_";
194 case Type::StructTyID: return "struct_";
195 case Type::ArrayTyID: return "array_";
196 case Type::PointerTyID: return "ptr_";
197 case Type::VectorTyID: return "packed_";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000198 default: return "other_";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000199 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000200 return "unknown_";
201}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000202
Chris Lattner7e6d7452010-06-21 23:12:56 +0000203void CppWriter::error(const std::string& msg) {
204 report_fatal_error(msg);
205}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000206
Chris Lattner7e6d7452010-06-21 23:12:56 +0000207// printCFP - Print a floating point constant .. very carefully :)
208// This makes sure that conversion to/from floating yields the same binary
209// result so that we don't lose precision.
210void CppWriter::printCFP(const ConstantFP *CFP) {
211 bool ignored;
212 APFloat APF = APFloat(CFP->getValueAPF()); // copy
213 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
214 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
215 Out << "ConstantFP::get(mod->getContext(), ";
216 Out << "APFloat(";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000217#if HAVE_PRINTF_A
Chris Lattner7e6d7452010-06-21 23:12:56 +0000218 char Buffer[100];
219 sprintf(Buffer, "%A", APF.convertToDouble());
220 if ((!strncmp(Buffer, "0x", 2) ||
221 !strncmp(Buffer, "-0x", 3) ||
222 !strncmp(Buffer, "+0x", 3)) &&
223 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
224 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
225 Out << "BitsToDouble(" << Buffer << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000226 else
Chris Lattner7e6d7452010-06-21 23:12:56 +0000227 Out << "BitsToFloat((float)" << Buffer << ")";
228 Out << ")";
229 } else {
230#endif
231 std::string StrVal = ftostr(CFP->getValueAPF());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000232
Chris Lattner7e6d7452010-06-21 23:12:56 +0000233 while (StrVal[0] == ' ')
234 StrVal.erase(StrVal.begin());
235
236 // Check to make sure that the stringized number is not some string like
237 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
238 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
239 ((StrVal[0] == '-' || StrVal[0] == '+') &&
240 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
241 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
242 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
243 Out << StrVal;
244 else
245 Out << StrVal << "f";
246 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
247 Out << "BitsToDouble(0x"
248 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
249 << "ULL) /* " << StrVal << " */";
250 else
251 Out << "BitsToFloat(0x"
252 << utohexstr((uint32_t)CFP->getValueAPF().
253 bitcastToAPInt().getZExtValue())
254 << "U) /* " << StrVal << " */";
255 Out << ")";
256#if HAVE_PRINTF_A
257 }
258#endif
259 Out << ")";
260}
261
262void CppWriter::printCallingConv(CallingConv::ID cc){
263 // Print the calling convention.
264 switch (cc) {
265 case CallingConv::C: Out << "CallingConv::C"; break;
266 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
267 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
268 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
269 default: Out << cc; break;
270 }
271}
272
273void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
274 switch (LT) {
275 case GlobalValue::InternalLinkage:
276 Out << "GlobalValue::InternalLinkage"; break;
277 case GlobalValue::PrivateLinkage:
278 Out << "GlobalValue::PrivateLinkage"; break;
279 case GlobalValue::LinkerPrivateLinkage:
280 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Bill Wendling5e721d72010-07-01 21:55:59 +0000281 case GlobalValue::LinkerPrivateWeakLinkage:
282 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
Bill Wendling55ae5152010-08-20 22:05:50 +0000283 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
284 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000285 case GlobalValue::AvailableExternallyLinkage:
286 Out << "GlobalValue::AvailableExternallyLinkage "; break;
287 case GlobalValue::LinkOnceAnyLinkage:
288 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
289 case GlobalValue::LinkOnceODRLinkage:
290 Out << "GlobalValue::LinkOnceODRLinkage "; break;
291 case GlobalValue::WeakAnyLinkage:
292 Out << "GlobalValue::WeakAnyLinkage"; break;
293 case GlobalValue::WeakODRLinkage:
294 Out << "GlobalValue::WeakODRLinkage"; break;
295 case GlobalValue::AppendingLinkage:
296 Out << "GlobalValue::AppendingLinkage"; break;
297 case GlobalValue::ExternalLinkage:
298 Out << "GlobalValue::ExternalLinkage"; break;
299 case GlobalValue::DLLImportLinkage:
300 Out << "GlobalValue::DLLImportLinkage"; break;
301 case GlobalValue::DLLExportLinkage:
302 Out << "GlobalValue::DLLExportLinkage"; break;
303 case GlobalValue::ExternalWeakLinkage:
304 Out << "GlobalValue::ExternalWeakLinkage"; break;
305 case GlobalValue::CommonLinkage:
306 Out << "GlobalValue::CommonLinkage"; break;
307 }
308}
309
310void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
311 switch (VisType) {
312 default: llvm_unreachable("Unknown GVar visibility");
313 case GlobalValue::DefaultVisibility:
314 Out << "GlobalValue::DefaultVisibility";
315 break;
316 case GlobalValue::HiddenVisibility:
317 Out << "GlobalValue::HiddenVisibility";
318 break;
319 case GlobalValue::ProtectedVisibility:
320 Out << "GlobalValue::ProtectedVisibility";
321 break;
322 }
323}
324
325// printEscapedString - Print each character of the specified string, escaping
326// it if it is not printable or if it is an escape char.
327void CppWriter::printEscapedString(const std::string &Str) {
328 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
329 unsigned char C = Str[i];
330 if (isprint(C) && C != '"' && C != '\\') {
331 Out << C;
332 } else {
333 Out << "\\x"
334 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
335 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
336 }
337 }
338}
339
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000340std::string CppWriter::getCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000341 // First, handle the primitive types .. easy
342 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
343 switch (Ty->getTypeID()) {
344 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
345 case Type::IntegerTyID: {
346 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
347 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
348 }
349 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
350 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
351 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
352 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
Dale Johannesenbb811a22010-09-10 20:55:01 +0000353 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000354 default:
355 error("Invalid primitive type");
356 break;
357 }
358 // shouldn't be returned, but make it sensible
359 return "Type::getVoidTy(mod->getContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000360 }
361
Chris Lattner7e6d7452010-06-21 23:12:56 +0000362 // Now, see if we've seen the type before and return that
363 TypeMap::iterator I = TypeNames.find(Ty);
364 if (I != TypeNames.end())
365 return I->second;
366
367 // Okay, let's build a new name for this type. Start with a prefix
368 const char* prefix = 0;
369 switch (Ty->getTypeID()) {
370 case Type::FunctionTyID: prefix = "FuncTy_"; break;
371 case Type::StructTyID: prefix = "StructTy_"; break;
372 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
373 case Type::PointerTyID: prefix = "PointerTy_"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000374 case Type::VectorTyID: prefix = "VectorTy_"; break;
375 default: prefix = "OtherTy_"; break; // prevent breakage
Anton Korobeynikov50276522008-04-23 22:29:24 +0000376 }
377
Chris Lattner7e6d7452010-06-21 23:12:56 +0000378 // See if the type has a name in the symboltable and build accordingly
Chris Lattner7e6d7452010-06-21 23:12:56 +0000379 std::string name;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000380 if (StructType *STy = dyn_cast<StructType>(Ty))
Chris Lattner1afcace2011-07-09 17:41:24 +0000381 if (STy->hasName())
382 name = STy->getName();
383
384 if (name.empty())
385 name = utostr(uniqueNum++);
386
387 name = std::string(prefix) + name;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000388 sanitize(name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000389
Chris Lattner7e6d7452010-06-21 23:12:56 +0000390 // Save the name
391 return TypeNames[Ty] = name;
392}
393
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000394void CppWriter::printCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000395 printEscapedString(getCppName(Ty));
396}
397
398std::string CppWriter::getCppName(const Value* val) {
399 std::string name;
400 ValueMap::iterator I = ValueNames.find(val);
401 if (I != ValueNames.end() && I->first == val)
402 return I->second;
403
404 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
405 name = std::string("gvar_") +
406 getTypePrefix(GV->getType()->getElementType());
407 } else if (isa<Function>(val)) {
408 name = std::string("func_");
409 } else if (const Constant* C = dyn_cast<Constant>(val)) {
410 name = std::string("const_") + getTypePrefix(C->getType());
411 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
412 if (is_inline) {
413 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
414 Function::const_arg_iterator(Arg)) + 1;
415 name = std::string("arg_") + utostr(argNum);
416 NameSet::iterator NI = UsedNames.find(name);
417 if (NI != UsedNames.end())
418 name += std::string("_") + utostr(uniqueNum++);
419 UsedNames.insert(name);
420 return ValueNames[val] = name;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000421 } else {
422 name = getTypePrefix(val->getType());
423 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000424 } else {
425 name = getTypePrefix(val->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000426 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000427 if (val->hasName())
428 name += val->getName();
429 else
430 name += utostr(uniqueNum++);
431 sanitize(name);
432 NameSet::iterator NI = UsedNames.find(name);
433 if (NI != UsedNames.end())
434 name += std::string("_") + utostr(uniqueNum++);
435 UsedNames.insert(name);
436 return ValueNames[val] = name;
437}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000438
Chris Lattner7e6d7452010-06-21 23:12:56 +0000439void CppWriter::printCppName(const Value* val) {
440 printEscapedString(getCppName(val));
441}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000442
Chris Lattner7e6d7452010-06-21 23:12:56 +0000443void CppWriter::printAttributes(const AttrListPtr &PAL,
444 const std::string &name) {
445 Out << "AttrListPtr " << name << "_PAL;";
446 nl(Out);
447 if (!PAL.isEmpty()) {
448 Out << '{'; in(); nl(Out);
449 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
450 Out << "AttributeWithIndex PAWI;"; nl(Out);
451 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
452 unsigned index = PAL.getSlot(i).Index;
453 Attributes attrs = PAL.getSlot(i).Attrs;
454 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
Chris Lattneracca9552009-01-13 07:22:22 +0000455#define HANDLE_ATTR(X) \
Chris Lattner7e6d7452010-06-21 23:12:56 +0000456 if (attrs & Attribute::X) \
457 Out << " | Attribute::" #X; \
458 attrs &= ~Attribute::X;
459
460 HANDLE_ATTR(SExt);
461 HANDLE_ATTR(ZExt);
462 HANDLE_ATTR(NoReturn);
463 HANDLE_ATTR(InReg);
464 HANDLE_ATTR(StructRet);
465 HANDLE_ATTR(NoUnwind);
466 HANDLE_ATTR(NoAlias);
467 HANDLE_ATTR(ByVal);
468 HANDLE_ATTR(Nest);
469 HANDLE_ATTR(ReadNone);
470 HANDLE_ATTR(ReadOnly);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000471 HANDLE_ATTR(NoInline);
472 HANDLE_ATTR(AlwaysInline);
473 HANDLE_ATTR(OptimizeForSize);
474 HANDLE_ATTR(StackProtect);
475 HANDLE_ATTR(StackProtectReq);
476 HANDLE_ATTR(NoCapture);
Eli Friedman32bb4df2010-07-16 18:47:20 +0000477 HANDLE_ATTR(NoRedZone);
478 HANDLE_ATTR(NoImplicitFloat);
479 HANDLE_ATTR(Naked);
480 HANDLE_ATTR(InlineHint);
Chris Lattneracca9552009-01-13 07:22:22 +0000481#undef HANDLE_ATTR
Eli Friedman32bb4df2010-07-16 18:47:20 +0000482 if (attrs & Attribute::StackAlignment)
483 Out << " | Attribute::constructStackAlignmentFromInt("
484 << Attribute::getStackAlignmentFromAttrs(attrs)
485 << ")";
486 attrs &= ~Attribute::StackAlignment;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000487 assert(attrs == 0 && "Unhandled attribute!");
488 Out << ";";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000489 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000490 Out << "Attrs.push_back(PAWI);";
491 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000492 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000493 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
494 nl(Out);
495 out(); nl(Out);
496 Out << '}'; nl(Out);
497 }
498}
499
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000500void CppWriter::printType(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000501 // We don't print definitions for primitive types
502 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000503 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000504
505 // If we already defined this type, we don't need to define it again.
506 if (DefinedTypes.find(Ty) != DefinedTypes.end())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000507 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000508
509 // Everything below needs the name for the type so get it now.
510 std::string typeName(getCppName(Ty));
511
Chris Lattner7e6d7452010-06-21 23:12:56 +0000512 // Print the type definition
513 switch (Ty->getTypeID()) {
514 case Type::FunctionTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000515 FunctionType* FT = cast<FunctionType>(Ty);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000516 Out << "std::vector<Type*>" << typeName << "_args;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000517 nl(Out);
518 FunctionType::param_iterator PI = FT->param_begin();
519 FunctionType::param_iterator PE = FT->param_end();
520 for (; PI != PE; ++PI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000521 Type* argTy = static_cast<Type*>(*PI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000522 printType(argTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000523 std::string argName(getCppName(argTy));
524 Out << typeName << "_args.push_back(" << argName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000525 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000526 nl(Out);
527 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000528 printType(FT->getReturnType());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000529 std::string retTypeName(getCppName(FT->getReturnType()));
530 Out << "FunctionType* " << typeName << " = FunctionType::get(";
531 in(); nl(Out) << "/*Result=*/" << retTypeName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000532 Out << ",";
533 nl(Out) << "/*Params=*/" << typeName << "_args,";
534 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
535 out();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000536 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000537 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000538 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000539 case Type::StructTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000540 StructType* ST = cast<StructType>(Ty);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000541 if (!ST->isAnonymous()) {
542 Out << "StructType *" << typeName << " = ";
543 Out << "StructType::createNamed(mod->getContext(), \"";
544 printEscapedString(ST->getName());
545 Out << "\");";
546 nl(Out);
547 // Indicate that this type is now defined.
548 DefinedTypes.insert(Ty);
549 }
550
551 Out << "std::vector<Type*>" << typeName << "_fields;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000552 nl(Out);
553 StructType::element_iterator EI = ST->element_begin();
554 StructType::element_iterator EE = ST->element_end();
555 for (; EI != EE; ++EI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000556 Type* fieldTy = static_cast<Type*>(*EI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000557 printType(fieldTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000558 std::string fieldName(getCppName(fieldTy));
559 Out << typeName << "_fields.push_back(" << fieldName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000560 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000561 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000562 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000563
Chris Lattner1afcace2011-07-09 17:41:24 +0000564 if (ST->isAnonymous()) {
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000565 Out << "StructType *" << typeName << " = ";
Chris Lattner1afcace2011-07-09 17:41:24 +0000566 Out << "StructType::get(" << "mod->getContext(), ";
567 } else {
Chris Lattner1afcace2011-07-09 17:41:24 +0000568 Out << typeName << "->setBody(";
569 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000570
Chris Lattner1afcace2011-07-09 17:41:24 +0000571 Out << typeName << "_fields, /*isPacked=*/"
Chris Lattner7e6d7452010-06-21 23:12:56 +0000572 << (ST->isPacked() ? "true" : "false") << ");";
573 nl(Out);
574 break;
575 }
576 case Type::ArrayTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000577 ArrayType* AT = cast<ArrayType>(Ty);
578 Type* ET = AT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000579 printType(ET);
580 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
581 std::string elemName(getCppName(ET));
582 Out << "ArrayType* " << typeName << " = ArrayType::get("
583 << elemName
584 << ", " << utostr(AT->getNumElements()) << ");";
585 nl(Out);
586 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000587 break;
588 }
589 case Type::PointerTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000590 PointerType* PT = cast<PointerType>(Ty);
591 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000592 printType(ET);
593 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
594 std::string elemName(getCppName(ET));
595 Out << "PointerType* " << typeName << " = PointerType::get("
596 << elemName
597 << ", " << utostr(PT->getAddressSpace()) << ");";
598 nl(Out);
599 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000600 break;
601 }
602 case Type::VectorTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000603 VectorType* PT = cast<VectorType>(Ty);
604 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000605 printType(ET);
606 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
607 std::string elemName(getCppName(ET));
608 Out << "VectorType* " << typeName << " = VectorType::get("
609 << elemName
610 << ", " << utostr(PT->getNumElements()) << ");";
611 nl(Out);
612 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000613 break;
614 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000615 default:
616 error("Invalid TypeID");
617 }
618
Chris Lattner7e6d7452010-06-21 23:12:56 +0000619 // Indicate that this type is now defined.
620 DefinedTypes.insert(Ty);
621
Chris Lattner7e6d7452010-06-21 23:12:56 +0000622 // Finally, separate the type definition from other with a newline.
623 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000624}
625
626void CppWriter::printTypes(const Module* M) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000627 // Add all of the global variables to the value table.
Chris Lattner7e6d7452010-06-21 23:12:56 +0000628 for (Module::const_global_iterator I = TheModule->global_begin(),
629 E = TheModule->global_end(); I != E; ++I) {
630 if (I->hasInitializer())
631 printType(I->getInitializer()->getType());
632 printType(I->getType());
633 }
634
635 // Add all the functions to the table
636 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
637 FI != FE; ++FI) {
638 printType(FI->getReturnType());
639 printType(FI->getFunctionType());
640 // Add all the function arguments
641 for (Function::const_arg_iterator AI = FI->arg_begin(),
642 AE = FI->arg_end(); AI != AE; ++AI) {
643 printType(AI->getType());
644 }
645
646 // Add all of the basic blocks and instructions
647 for (Function::const_iterator BB = FI->begin(),
648 E = FI->end(); BB != E; ++BB) {
649 printType(BB->getType());
650 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
651 ++I) {
652 printType(I->getType());
653 for (unsigned i = 0; i < I->getNumOperands(); ++i)
654 printType(I->getOperand(i)->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000655 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000656 }
657 }
658}
659
660
661// printConstant - Print out a constant pool entry...
662void CppWriter::printConstant(const Constant *CV) {
663 // First, if the constant is actually a GlobalValue (variable or function)
664 // or its already in the constant list then we've printed it already and we
665 // can just return.
666 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
667 return;
668
669 std::string constName(getCppName(CV));
670 std::string typeName(getCppName(CV->getType()));
671
672 if (isa<GlobalValue>(CV)) {
673 // Skip variables and functions, we emit them elsewhere
674 return;
675 }
676
677 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
678 std::string constValue = CI->getValue().toString(10, true);
679 Out << "ConstantInt* " << constName
680 << " = ConstantInt::get(mod->getContext(), APInt("
681 << cast<IntegerType>(CI->getType())->getBitWidth()
682 << ", StringRef(\"" << constValue << "\"), 10));";
683 } else if (isa<ConstantAggregateZero>(CV)) {
684 Out << "ConstantAggregateZero* " << constName
685 << " = ConstantAggregateZero::get(" << typeName << ");";
686 } else if (isa<ConstantPointerNull>(CV)) {
687 Out << "ConstantPointerNull* " << constName
688 << " = ConstantPointerNull::get(" << typeName << ");";
689 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
690 Out << "ConstantFP* " << constName << " = ";
691 printCFP(CFP);
692 Out << ";";
693 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
694 if (CA->isString() &&
695 CA->getType()->getElementType() ==
696 Type::getInt8Ty(CA->getContext())) {
697 Out << "Constant* " << constName <<
698 " = ConstantArray::get(mod->getContext(), \"";
699 std::string tmp = CA->getAsString();
700 bool nullTerminate = false;
701 if (tmp[tmp.length()-1] == 0) {
702 tmp.erase(tmp.length()-1);
703 nullTerminate = true;
704 }
705 printEscapedString(tmp);
706 // Determine if we want null termination or not.
707 if (nullTerminate)
708 Out << "\", true"; // Indicate that the null terminator should be
709 // added.
710 else
711 Out << "\", false";// No null terminator
712 Out << ");";
713 } else {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000714 Out << "std::vector<Constant*> " << constName << "_elems;";
715 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000716 unsigned N = CA->getNumOperands();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000717 for (unsigned i = 0; i < N; ++i) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000718 printConstant(CA->getOperand(i)); // recurse to print operands
Anton Korobeynikov50276522008-04-23 22:29:24 +0000719 Out << constName << "_elems.push_back("
Chris Lattner7e6d7452010-06-21 23:12:56 +0000720 << getCppName(CA->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000721 nl(Out);
722 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000723 Out << "Constant* " << constName << " = ConstantArray::get("
Anton Korobeynikov50276522008-04-23 22:29:24 +0000724 << typeName << ", " << constName << "_elems);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000725 }
726 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
727 Out << "std::vector<Constant*> " << constName << "_fields;";
728 nl(Out);
729 unsigned N = CS->getNumOperands();
730 for (unsigned i = 0; i < N; i++) {
731 printConstant(CS->getOperand(i));
732 Out << constName << "_fields.push_back("
733 << getCppName(CS->getOperand(i)) << ");";
734 nl(Out);
735 }
736 Out << "Constant* " << constName << " = ConstantStruct::get("
737 << typeName << ", " << constName << "_fields);";
738 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
739 Out << "std::vector<Constant*> " << constName << "_elems;";
740 nl(Out);
741 unsigned N = CP->getNumOperands();
742 for (unsigned i = 0; i < N; ++i) {
743 printConstant(CP->getOperand(i));
744 Out << constName << "_elems.push_back("
745 << getCppName(CP->getOperand(i)) << ");";
746 nl(Out);
747 }
748 Out << "Constant* " << constName << " = ConstantVector::get("
749 << typeName << ", " << constName << "_elems);";
750 } else if (isa<UndefValue>(CV)) {
751 Out << "UndefValue* " << constName << " = UndefValue::get("
752 << typeName << ");";
753 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
754 if (CE->getOpcode() == Instruction::GetElementPtr) {
755 Out << "std::vector<Constant*> " << constName << "_indices;";
756 nl(Out);
757 printConstant(CE->getOperand(0));
758 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
759 printConstant(CE->getOperand(i));
760 Out << constName << "_indices.push_back("
761 << getCppName(CE->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000762 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000763 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000764 Out << "Constant* " << constName
765 << " = ConstantExpr::getGetElementPtr("
766 << getCppName(CE->getOperand(0)) << ", "
767 << "&" << constName << "_indices[0], "
768 << constName << "_indices.size()"
769 << ");";
770 } else if (CE->isCast()) {
771 printConstant(CE->getOperand(0));
772 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
773 switch (CE->getOpcode()) {
774 default: llvm_unreachable("Invalid cast opcode");
775 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
776 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
777 case Instruction::SExt: Out << "Instruction::SExt"; break;
778 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
779 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
780 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
781 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
782 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
783 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
784 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
785 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
786 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
787 }
788 Out << ", " << getCppName(CE->getOperand(0)) << ", "
789 << getCppName(CE->getType()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000790 } else {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000791 unsigned N = CE->getNumOperands();
792 for (unsigned i = 0; i < N; ++i ) {
793 printConstant(CE->getOperand(i));
794 }
795 Out << "Constant* " << constName << " = ConstantExpr::";
796 switch (CE->getOpcode()) {
797 case Instruction::Add: Out << "getAdd("; break;
798 case Instruction::FAdd: Out << "getFAdd("; break;
799 case Instruction::Sub: Out << "getSub("; break;
800 case Instruction::FSub: Out << "getFSub("; break;
801 case Instruction::Mul: Out << "getMul("; break;
802 case Instruction::FMul: Out << "getFMul("; break;
803 case Instruction::UDiv: Out << "getUDiv("; break;
804 case Instruction::SDiv: Out << "getSDiv("; break;
805 case Instruction::FDiv: Out << "getFDiv("; break;
806 case Instruction::URem: Out << "getURem("; break;
807 case Instruction::SRem: Out << "getSRem("; break;
808 case Instruction::FRem: Out << "getFRem("; break;
809 case Instruction::And: Out << "getAnd("; break;
810 case Instruction::Or: Out << "getOr("; break;
811 case Instruction::Xor: Out << "getXor("; break;
812 case Instruction::ICmp:
813 Out << "getICmp(ICmpInst::ICMP_";
814 switch (CE->getPredicate()) {
815 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
816 case ICmpInst::ICMP_NE: Out << "NE"; break;
817 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
818 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
819 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
820 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
821 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
822 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
823 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
824 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
825 default: error("Invalid ICmp Predicate");
826 }
827 break;
828 case Instruction::FCmp:
829 Out << "getFCmp(FCmpInst::FCMP_";
830 switch (CE->getPredicate()) {
831 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
832 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
833 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
834 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
835 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
836 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
837 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
838 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
839 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
840 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
841 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
842 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
843 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
844 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
845 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
846 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
847 default: error("Invalid FCmp Predicate");
848 }
849 break;
850 case Instruction::Shl: Out << "getShl("; break;
851 case Instruction::LShr: Out << "getLShr("; break;
852 case Instruction::AShr: Out << "getAShr("; break;
853 case Instruction::Select: Out << "getSelect("; break;
854 case Instruction::ExtractElement: Out << "getExtractElement("; break;
855 case Instruction::InsertElement: Out << "getInsertElement("; break;
856 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
857 default:
858 error("Invalid constant expression");
859 break;
860 }
861 Out << getCppName(CE->getOperand(0));
862 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
863 Out << ", " << getCppName(CE->getOperand(i));
864 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000865 }
Chris Lattner32848772010-06-21 23:19:36 +0000866 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
867 Out << "Constant* " << constName << " = ";
868 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000869 } else {
870 error("Bad Constant");
871 Out << "Constant* " << constName << " = 0; ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000872 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000873 nl(Out);
874}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000875
Chris Lattner7e6d7452010-06-21 23:12:56 +0000876void CppWriter::printConstants(const Module* M) {
877 // Traverse all the global variables looking for constant initializers
878 for (Module::const_global_iterator I = TheModule->global_begin(),
879 E = TheModule->global_end(); I != E; ++I)
880 if (I->hasInitializer())
881 printConstant(I->getInitializer());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000882
Chris Lattner7e6d7452010-06-21 23:12:56 +0000883 // Traverse the LLVM functions looking for constants
884 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
885 FI != FE; ++FI) {
886 // Add all of the basic blocks and instructions
887 for (Function::const_iterator BB = FI->begin(),
888 E = FI->end(); BB != E; ++BB) {
889 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
890 ++I) {
891 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
892 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
893 printConstant(C);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000894 }
895 }
896 }
897 }
898 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000899}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000900
Chris Lattner7e6d7452010-06-21 23:12:56 +0000901void CppWriter::printVariableUses(const GlobalVariable *GV) {
902 nl(Out) << "// Type Definitions";
903 nl(Out);
904 printType(GV->getType());
905 if (GV->hasInitializer()) {
Jay Foad7d715df2011-06-19 18:37:11 +0000906 const Constant *Init = GV->getInitializer();
Chris Lattner7e6d7452010-06-21 23:12:56 +0000907 printType(Init->getType());
Jay Foad7d715df2011-06-19 18:37:11 +0000908 if (const Function *F = dyn_cast<Function>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000909 nl(Out)<< "/ Function Declarations"; nl(Out);
910 printFunctionHead(F);
Jay Foad7d715df2011-06-19 18:37:11 +0000911 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000912 nl(Out) << "// Global Variable Declarations"; nl(Out);
913 printVariableHead(gv);
914
915 nl(Out) << "// Global Variable Definitions"; nl(Out);
916 printVariableBody(gv);
917 } else {
918 nl(Out) << "// Constant Definitions"; nl(Out);
919 printConstant(Init);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000920 }
921 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000922}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000923
Chris Lattner7e6d7452010-06-21 23:12:56 +0000924void CppWriter::printVariableHead(const GlobalVariable *GV) {
925 nl(Out) << "GlobalVariable* " << getCppName(GV);
926 if (is_inline) {
927 Out << " = mod->getGlobalVariable(mod->getContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000928 printEscapedString(GV->getName());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000929 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
930 nl(Out) << "if (!" << getCppName(GV) << ") {";
931 in(); nl(Out) << getCppName(GV);
932 }
933 Out << " = new GlobalVariable(/*Module=*/*mod, ";
934 nl(Out) << "/*Type=*/";
935 printCppName(GV->getType()->getElementType());
936 Out << ",";
937 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
938 Out << ",";
939 nl(Out) << "/*Linkage=*/";
940 printLinkageType(GV->getLinkage());
941 Out << ",";
942 nl(Out) << "/*Initializer=*/0, ";
943 if (GV->hasInitializer()) {
944 Out << "// has initializer, specified below";
945 }
946 nl(Out) << "/*Name=*/\"";
947 printEscapedString(GV->getName());
948 Out << "\");";
949 nl(Out);
950
951 if (GV->hasSection()) {
952 printCppName(GV);
953 Out << "->setSection(\"";
954 printEscapedString(GV->getSection());
Owen Anderson16a412e2009-07-10 16:42:19 +0000955 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000956 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000957 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000958 if (GV->getAlignment()) {
959 printCppName(GV);
960 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000961 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000962 }
963 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
964 printCppName(GV);
965 Out << "->setVisibility(";
966 printVisibilityType(GV->getVisibility());
967 Out << ");";
968 nl(Out);
969 }
970 if (GV->isThreadLocal()) {
971 printCppName(GV);
972 Out << "->setThreadLocal(true);";
973 nl(Out);
974 }
975 if (is_inline) {
976 out(); Out << "}"; nl(Out);
977 }
978}
979
980void CppWriter::printVariableBody(const GlobalVariable *GV) {
981 if (GV->hasInitializer()) {
982 printCppName(GV);
983 Out << "->setInitializer(";
984 Out << getCppName(GV->getInitializer()) << ");";
985 nl(Out);
986 }
987}
988
989std::string CppWriter::getOpName(Value* V) {
990 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
991 return getCppName(V);
992
993 // See if its alread in the map of forward references, if so just return the
994 // name we already set up for it
995 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
996 if (I != ForwardRefs.end())
997 return I->second;
998
999 // This is a new forward reference. Generate a unique name for it
1000 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1001
1002 // Yes, this is a hack. An Argument is the smallest instantiable value that
1003 // we can make as a placeholder for the real value. We'll replace these
1004 // Argument instances later.
1005 Out << "Argument* " << result << " = new Argument("
1006 << getCppName(V->getType()) << ");";
1007 nl(Out);
1008 ForwardRefs[V] = result;
1009 return result;
1010}
1011
1012// printInstruction - This member is called for each Instruction in a function.
1013void CppWriter::printInstruction(const Instruction *I,
1014 const std::string& bbname) {
1015 std::string iName(getCppName(I));
1016
1017 // Before we emit this instruction, we need to take care of generating any
1018 // forward references. So, we get the names of all the operands in advance
1019 const unsigned Ops(I->getNumOperands());
1020 std::string* opNames = new std::string[Ops];
Chris Lattner32848772010-06-21 23:19:36 +00001021 for (unsigned i = 0; i < Ops; i++)
Chris Lattner7e6d7452010-06-21 23:12:56 +00001022 opNames[i] = getOpName(I->getOperand(i));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001023
Chris Lattner7e6d7452010-06-21 23:12:56 +00001024 switch (I->getOpcode()) {
1025 default:
1026 error("Invalid instruction");
1027 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001028
Chris Lattner7e6d7452010-06-21 23:12:56 +00001029 case Instruction::Ret: {
1030 const ReturnInst* ret = cast<ReturnInst>(I);
1031 Out << "ReturnInst::Create(mod->getContext(), "
1032 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1033 break;
1034 }
1035 case Instruction::Br: {
1036 const BranchInst* br = cast<BranchInst>(I);
1037 Out << "BranchInst::Create(" ;
Chris Lattner32848772010-06-21 23:19:36 +00001038 if (br->getNumOperands() == 3) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001039 Out << opNames[2] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001040 << opNames[1] << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001041 << opNames[0] << ", ";
1042
1043 } else if (br->getNumOperands() == 1) {
1044 Out << opNames[0] << ", ";
1045 } else {
1046 error("Branch with 2 operands?");
1047 }
1048 Out << bbname << ");";
1049 break;
1050 }
1051 case Instruction::Switch: {
1052 const SwitchInst *SI = cast<SwitchInst>(I);
1053 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1054 << opNames[0] << ", "
1055 << opNames[1] << ", "
1056 << SI->getNumCases() << ", " << bbname << ");";
1057 nl(Out);
1058 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
1059 Out << iName << "->addCase("
1060 << opNames[i] << ", "
1061 << opNames[i+1] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001062 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001063 }
1064 break;
1065 }
1066 case Instruction::IndirectBr: {
1067 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1068 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1069 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1070 nl(Out);
1071 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1072 Out << iName << "->addDestination(" << opNames[i] << ");";
1073 nl(Out);
1074 }
1075 break;
1076 }
1077 case Instruction::Invoke: {
1078 const InvokeInst* inv = cast<InvokeInst>(I);
1079 Out << "std::vector<Value*> " << iName << "_params;";
1080 nl(Out);
1081 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1082 Out << iName << "_params.push_back("
1083 << getOpName(inv->getArgOperand(i)) << ");";
1084 nl(Out);
1085 }
1086 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1087 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1088 << getOpName(inv->getCalledFunction()) << ", "
1089 << getOpName(inv->getNormalDest()) << ", "
1090 << getOpName(inv->getUnwindDest()) << ", "
1091 << iName << "_params.begin(), "
1092 << iName << "_params.end(), \"";
1093 printEscapedString(inv->getName());
1094 Out << "\", " << bbname << ");";
1095 nl(Out) << iName << "->setCallingConv(";
1096 printCallingConv(inv->getCallingConv());
1097 Out << ");";
1098 printAttributes(inv->getAttributes(), iName);
1099 Out << iName << "->setAttributes(" << iName << "_PAL);";
1100 nl(Out);
1101 break;
1102 }
1103 case Instruction::Unwind: {
1104 Out << "new UnwindInst("
1105 << bbname << ");";
1106 break;
1107 }
1108 case Instruction::Unreachable: {
1109 Out << "new UnreachableInst("
1110 << "mod->getContext(), "
1111 << bbname << ");";
1112 break;
1113 }
1114 case Instruction::Add:
1115 case Instruction::FAdd:
1116 case Instruction::Sub:
1117 case Instruction::FSub:
1118 case Instruction::Mul:
1119 case Instruction::FMul:
1120 case Instruction::UDiv:
1121 case Instruction::SDiv:
1122 case Instruction::FDiv:
1123 case Instruction::URem:
1124 case Instruction::SRem:
1125 case Instruction::FRem:
1126 case Instruction::And:
1127 case Instruction::Or:
1128 case Instruction::Xor:
1129 case Instruction::Shl:
1130 case Instruction::LShr:
1131 case Instruction::AShr:{
1132 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1133 switch (I->getOpcode()) {
1134 case Instruction::Add: Out << "Instruction::Add"; break;
1135 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1136 case Instruction::Sub: Out << "Instruction::Sub"; break;
1137 case Instruction::FSub: Out << "Instruction::FSub"; break;
1138 case Instruction::Mul: Out << "Instruction::Mul"; break;
1139 case Instruction::FMul: Out << "Instruction::FMul"; break;
1140 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1141 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1142 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1143 case Instruction::URem:Out << "Instruction::URem"; break;
1144 case Instruction::SRem:Out << "Instruction::SRem"; break;
1145 case Instruction::FRem:Out << "Instruction::FRem"; break;
1146 case Instruction::And: Out << "Instruction::And"; break;
1147 case Instruction::Or: Out << "Instruction::Or"; break;
1148 case Instruction::Xor: Out << "Instruction::Xor"; break;
1149 case Instruction::Shl: Out << "Instruction::Shl"; break;
1150 case Instruction::LShr:Out << "Instruction::LShr"; break;
1151 case Instruction::AShr:Out << "Instruction::AShr"; break;
1152 default: Out << "Instruction::BadOpCode"; break;
1153 }
1154 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1155 printEscapedString(I->getName());
1156 Out << "\", " << bbname << ");";
1157 break;
1158 }
1159 case Instruction::FCmp: {
1160 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1161 switch (cast<FCmpInst>(I)->getPredicate()) {
1162 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1163 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1164 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1165 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1166 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1167 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1168 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1169 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1170 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1171 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1172 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1173 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1174 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1175 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1176 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1177 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1178 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1179 }
1180 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1181 printEscapedString(I->getName());
1182 Out << "\");";
1183 break;
1184 }
1185 case Instruction::ICmp: {
1186 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1187 switch (cast<ICmpInst>(I)->getPredicate()) {
1188 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1189 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1190 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1191 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1192 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1193 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1194 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1195 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1196 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1197 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1198 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1199 }
1200 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1201 printEscapedString(I->getName());
1202 Out << "\");";
1203 break;
1204 }
1205 case Instruction::Alloca: {
1206 const AllocaInst* allocaI = cast<AllocaInst>(I);
1207 Out << "AllocaInst* " << iName << " = new AllocaInst("
1208 << getCppName(allocaI->getAllocatedType()) << ", ";
1209 if (allocaI->isArrayAllocation())
1210 Out << opNames[0] << ", ";
1211 Out << "\"";
1212 printEscapedString(allocaI->getName());
1213 Out << "\", " << bbname << ");";
1214 if (allocaI->getAlignment())
1215 nl(Out) << iName << "->setAlignment("
1216 << allocaI->getAlignment() << ");";
1217 break;
1218 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001219 case Instruction::Load: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001220 const LoadInst* load = cast<LoadInst>(I);
1221 Out << "LoadInst* " << iName << " = new LoadInst("
1222 << opNames[0] << ", \"";
1223 printEscapedString(load->getName());
1224 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1225 << ", " << bbname << ");";
1226 break;
1227 }
1228 case Instruction::Store: {
1229 const StoreInst* store = cast<StoreInst>(I);
1230 Out << " new StoreInst("
1231 << opNames[0] << ", "
1232 << opNames[1] << ", "
1233 << (store->isVolatile() ? "true" : "false")
1234 << ", " << bbname << ");";
1235 break;
1236 }
1237 case Instruction::GetElementPtr: {
1238 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1239 if (gep->getNumOperands() <= 2) {
1240 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1241 << opNames[0];
1242 if (gep->getNumOperands() == 2)
1243 Out << ", " << opNames[1];
1244 } else {
1245 Out << "std::vector<Value*> " << iName << "_indices;";
1246 nl(Out);
1247 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1248 Out << iName << "_indices.push_back("
1249 << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001250 nl(Out);
1251 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001252 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1253 << opNames[0] << ", " << iName << "_indices.begin(), "
1254 << iName << "_indices.end()";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001255 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001256 Out << ", \"";
1257 printEscapedString(gep->getName());
1258 Out << "\", " << bbname << ");";
1259 break;
1260 }
1261 case Instruction::PHI: {
1262 const PHINode* phi = cast<PHINode>(I);
1263
1264 Out << "PHINode* " << iName << " = PHINode::Create("
Nicolas Geoffrayc6cf1972011-04-10 17:39:40 +00001265 << getCppName(phi->getType()) << ", "
Jay Foad3ecfc862011-03-30 11:28:46 +00001266 << phi->getNumIncomingValues() << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001267 printEscapedString(phi->getName());
1268 Out << "\", " << bbname << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001269 nl(Out);
Jay Foadc1371202011-06-20 14:18:48 +00001270 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001271 Out << iName << "->addIncoming("
Jay Foadc1371202011-06-20 14:18:48 +00001272 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
Jay Foad95c3e482011-06-23 09:09:15 +00001273 << getOpName(phi->getIncomingBlock(i)) << ");";
Chris Lattner627b4702009-10-27 21:24:48 +00001274 nl(Out);
Chris Lattner627b4702009-10-27 21:24:48 +00001275 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001276 break;
1277 }
1278 case Instruction::Trunc:
1279 case Instruction::ZExt:
1280 case Instruction::SExt:
1281 case Instruction::FPTrunc:
1282 case Instruction::FPExt:
1283 case Instruction::FPToUI:
1284 case Instruction::FPToSI:
1285 case Instruction::UIToFP:
1286 case Instruction::SIToFP:
1287 case Instruction::PtrToInt:
1288 case Instruction::IntToPtr:
1289 case Instruction::BitCast: {
1290 const CastInst* cst = cast<CastInst>(I);
1291 Out << "CastInst* " << iName << " = new ";
1292 switch (I->getOpcode()) {
1293 case Instruction::Trunc: Out << "TruncInst"; break;
1294 case Instruction::ZExt: Out << "ZExtInst"; break;
1295 case Instruction::SExt: Out << "SExtInst"; break;
1296 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1297 case Instruction::FPExt: Out << "FPExtInst"; break;
1298 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1299 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1300 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1301 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1302 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1303 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1304 case Instruction::BitCast: Out << "BitCastInst"; break;
1305 default: assert(!"Unreachable"); break;
1306 }
1307 Out << "(" << opNames[0] << ", "
1308 << getCppName(cst->getType()) << ", \"";
1309 printEscapedString(cst->getName());
1310 Out << "\", " << bbname << ");";
1311 break;
1312 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001313 case Instruction::Call: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001314 const CallInst* call = cast<CallInst>(I);
1315 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1316 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1317 << getCppName(ila->getFunctionType()) << ", \""
1318 << ila->getAsmString() << "\", \""
1319 << ila->getConstraintString() << "\","
1320 << (ila->hasSideEffects() ? "true" : "false") << ");";
1321 nl(Out);
1322 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001323 if (call->getNumArgOperands() > 1) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001324 Out << "std::vector<Value*> " << iName << "_params;";
1325 nl(Out);
Gabor Greif53ba5502010-07-02 19:08:46 +00001326 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
Gabor Greif63d024f2010-07-13 15:31:36 +00001327 Out << iName << "_params.push_back(" << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001328 nl(Out);
1329 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001330 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greifa3997812010-07-22 10:37:47 +00001331 << opNames[call->getNumArgOperands()] << ", "
1332 << iName << "_params.begin(), "
Bill Wendling22a5b292010-06-07 19:05:06 +00001333 << iName << "_params.end(), \"";
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001334 } else if (call->getNumArgOperands() == 1) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001335 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greif63d024f2010-07-13 15:31:36 +00001336 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001337 } else {
Gabor Greif63d024f2010-07-13 15:31:36 +00001338 Out << "CallInst* " << iName << " = CallInst::Create("
1339 << opNames[call->getNumArgOperands()] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001340 }
1341 printEscapedString(call->getName());
1342 Out << "\", " << bbname << ");";
1343 nl(Out) << iName << "->setCallingConv(";
1344 printCallingConv(call->getCallingConv());
1345 Out << ");";
1346 nl(Out) << iName << "->setTailCall("
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001347 << (call->isTailCall() ? "true" : "false");
Chris Lattner7e6d7452010-06-21 23:12:56 +00001348 Out << ");";
Gabor Greif135d7fe2010-07-02 19:26:28 +00001349 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001350 printAttributes(call->getAttributes(), iName);
1351 Out << iName << "->setAttributes(" << iName << "_PAL);";
1352 nl(Out);
1353 break;
1354 }
1355 case Instruction::Select: {
1356 const SelectInst* sel = cast<SelectInst>(I);
1357 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1358 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1359 printEscapedString(sel->getName());
1360 Out << "\", " << bbname << ");";
1361 break;
1362 }
1363 case Instruction::UserOp1:
1364 /// FALL THROUGH
1365 case Instruction::UserOp2: {
1366 /// FIXME: What should be done here?
1367 break;
1368 }
1369 case Instruction::VAArg: {
1370 const VAArgInst* va = cast<VAArgInst>(I);
1371 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1372 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1373 printEscapedString(va->getName());
1374 Out << "\", " << bbname << ");";
1375 break;
1376 }
1377 case Instruction::ExtractElement: {
1378 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1379 Out << "ExtractElementInst* " << getCppName(eei)
1380 << " = new ExtractElementInst(" << opNames[0]
1381 << ", " << opNames[1] << ", \"";
1382 printEscapedString(eei->getName());
1383 Out << "\", " << bbname << ");";
1384 break;
1385 }
1386 case Instruction::InsertElement: {
1387 const InsertElementInst* iei = cast<InsertElementInst>(I);
1388 Out << "InsertElementInst* " << getCppName(iei)
1389 << " = InsertElementInst::Create(" << opNames[0]
1390 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1391 printEscapedString(iei->getName());
1392 Out << "\", " << bbname << ");";
1393 break;
1394 }
1395 case Instruction::ShuffleVector: {
1396 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1397 Out << "ShuffleVectorInst* " << getCppName(svi)
1398 << " = new ShuffleVectorInst(" << opNames[0]
1399 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1400 printEscapedString(svi->getName());
1401 Out << "\", " << bbname << ");";
1402 break;
1403 }
1404 case Instruction::ExtractValue: {
1405 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1406 Out << "std::vector<unsigned> " << iName << "_indices;";
1407 nl(Out);
1408 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1409 Out << iName << "_indices.push_back("
1410 << evi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001411 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001412 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001413 Out << "ExtractValueInst* " << getCppName(evi)
1414 << " = ExtractValueInst::Create(" << opNames[0]
1415 << ", "
1416 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1417 printEscapedString(evi->getName());
1418 Out << "\", " << bbname << ");";
1419 break;
1420 }
1421 case Instruction::InsertValue: {
1422 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1423 Out << "std::vector<unsigned> " << iName << "_indices;";
1424 nl(Out);
1425 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1426 Out << iName << "_indices.push_back("
1427 << ivi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001428 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001429 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001430 Out << "InsertValueInst* " << getCppName(ivi)
1431 << " = InsertValueInst::Create(" << opNames[0]
1432 << ", " << opNames[1] << ", "
1433 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1434 printEscapedString(ivi->getName());
1435 Out << "\", " << bbname << ");";
1436 break;
1437 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001438 }
1439 DefinedValues.insert(I);
1440 nl(Out);
1441 delete [] opNames;
1442}
1443
Chris Lattner7e6d7452010-06-21 23:12:56 +00001444// Print out the types, constants and declarations needed by one function
1445void CppWriter::printFunctionUses(const Function* F) {
1446 nl(Out) << "// Type Definitions"; nl(Out);
1447 if (!is_inline) {
1448 // Print the function's return type
1449 printType(F->getReturnType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001450
Chris Lattner7e6d7452010-06-21 23:12:56 +00001451 // Print the function's function type
1452 printType(F->getFunctionType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001453
Chris Lattner7e6d7452010-06-21 23:12:56 +00001454 // Print the types of each of the function's arguments
Anton Korobeynikov50276522008-04-23 22:29:24 +00001455 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1456 AI != AE; ++AI) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001457 printType(AI->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001458 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001459 }
1460
Chris Lattner7e6d7452010-06-21 23:12:56 +00001461 // Print type definitions for every type referenced by an instruction and
1462 // make a note of any global values or constants that are referenced
1463 SmallPtrSet<GlobalValue*,64> gvs;
1464 SmallPtrSet<Constant*,64> consts;
1465 for (Function::const_iterator BB = F->begin(), BE = F->end();
1466 BB != BE; ++BB){
1467 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001468 I != E; ++I) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001469 // Print the type of the instruction itself
1470 printType(I->getType());
1471
1472 // Print the type of each of the instruction's operands
1473 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1474 Value* operand = I->getOperand(i);
1475 printType(operand->getType());
1476
1477 // If the operand references a GVal or Constant, make a note of it
1478 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1479 gvs.insert(GV);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001480 if (GenerationType != GenFunction)
1481 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1482 if (GVar->hasInitializer())
1483 consts.insert(GVar->getInitializer());
1484 } else if (Constant* C = dyn_cast<Constant>(operand)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001485 consts.insert(C);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001486 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1487 // If the operand references a GVal or Constant, make a note of it
1488 Value* operand = C->getOperand(j);
1489 printType(operand->getType());
1490 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1491 gvs.insert(GV);
1492 if (GenerationType != GenFunction)
1493 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1494 if (GVar->hasInitializer())
1495 consts.insert(GVar->getInitializer());
1496 }
1497 }
1498 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001499 }
1500 }
1501 }
1502
1503 // Print the function declarations for any functions encountered
1504 nl(Out) << "// Function Declarations"; nl(Out);
1505 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1506 I != E; ++I) {
1507 if (Function* Fun = dyn_cast<Function>(*I)) {
1508 if (!is_inline || Fun != F)
1509 printFunctionHead(Fun);
1510 }
1511 }
1512
1513 // Print the global variable declarations for any variables encountered
1514 nl(Out) << "// Global Variable Declarations"; nl(Out);
1515 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1516 I != E; ++I) {
1517 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1518 printVariableHead(F);
1519 }
1520
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001521 // Print the constants found
Chris Lattner7e6d7452010-06-21 23:12:56 +00001522 nl(Out) << "// Constant Definitions"; nl(Out);
1523 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1524 E = consts.end(); I != E; ++I) {
1525 printConstant(*I);
1526 }
1527
1528 // Process the global variables definitions now that all the constants have
1529 // been emitted. These definitions just couple the gvars with their constant
1530 // initializers.
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001531 if (GenerationType != GenFunction) {
1532 nl(Out) << "// Global Variable Definitions"; nl(Out);
1533 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1534 I != E; ++I) {
1535 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1536 printVariableBody(GV);
1537 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001538 }
1539}
1540
1541void CppWriter::printFunctionHead(const Function* F) {
1542 nl(Out) << "Function* " << getCppName(F);
1543 if (is_inline) {
1544 Out << " = mod->getFunction(\"";
1545 printEscapedString(F->getName());
1546 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1547 nl(Out) << "if (!" << getCppName(F) << ") {";
1548 nl(Out) << getCppName(F);
1549 }
1550 Out<< " = Function::Create(";
1551 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1552 nl(Out) << "/*Linkage=*/";
1553 printLinkageType(F->getLinkage());
1554 Out << ",";
1555 nl(Out) << "/*Name=*/\"";
1556 printEscapedString(F->getName());
1557 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1558 nl(Out,-1);
1559 printCppName(F);
1560 Out << "->setCallingConv(";
1561 printCallingConv(F->getCallingConv());
1562 Out << ");";
1563 nl(Out);
1564 if (F->hasSection()) {
1565 printCppName(F);
1566 Out << "->setSection(\"" << F->getSection() << "\");";
1567 nl(Out);
1568 }
1569 if (F->getAlignment()) {
1570 printCppName(F);
1571 Out << "->setAlignment(" << F->getAlignment() << ");";
1572 nl(Out);
1573 }
1574 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1575 printCppName(F);
1576 Out << "->setVisibility(";
1577 printVisibilityType(F->getVisibility());
1578 Out << ");";
1579 nl(Out);
1580 }
1581 if (F->hasGC()) {
1582 printCppName(F);
1583 Out << "->setGC(\"" << F->getGC() << "\");";
1584 nl(Out);
1585 }
1586 if (is_inline) {
1587 Out << "}";
1588 nl(Out);
1589 }
1590 printAttributes(F->getAttributes(), getCppName(F));
1591 printCppName(F);
1592 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1593 nl(Out);
1594}
1595
1596void CppWriter::printFunctionBody(const Function *F) {
1597 if (F->isDeclaration())
1598 return; // external functions have no bodies.
1599
1600 // Clear the DefinedValues and ForwardRefs maps because we can't have
1601 // cross-function forward refs
1602 ForwardRefs.clear();
1603 DefinedValues.clear();
1604
1605 // Create all the argument values
1606 if (!is_inline) {
1607 if (!F->arg_empty()) {
1608 Out << "Function::arg_iterator args = " << getCppName(F)
1609 << "->arg_begin();";
1610 nl(Out);
1611 }
1612 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1613 AI != AE; ++AI) {
1614 Out << "Value* " << getCppName(AI) << " = args++;";
1615 nl(Out);
1616 if (AI->hasName()) {
1617 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001618 nl(Out);
1619 }
1620 }
1621 }
1622
Chris Lattner7e6d7452010-06-21 23:12:56 +00001623 // Create all the basic blocks
1624 nl(Out);
1625 for (Function::const_iterator BI = F->begin(), BE = F->end();
1626 BI != BE; ++BI) {
1627 std::string bbname(getCppName(BI));
1628 Out << "BasicBlock* " << bbname <<
1629 " = BasicBlock::Create(mod->getContext(), \"";
1630 if (BI->hasName())
1631 printEscapedString(BI->getName());
1632 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1633 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001634 }
1635
Chris Lattner7e6d7452010-06-21 23:12:56 +00001636 // Output all of its basic blocks... for the function
1637 for (Function::const_iterator BI = F->begin(), BE = F->end();
1638 BI != BE; ++BI) {
1639 std::string bbname(getCppName(BI));
1640 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001641 nl(Out);
1642
Chris Lattner7e6d7452010-06-21 23:12:56 +00001643 // Output all of the instructions in the basic block...
1644 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1645 I != E; ++I) {
1646 printInstruction(I,bbname);
1647 }
1648 }
1649
1650 // Loop over the ForwardRefs and resolve them now that all instructions
1651 // are generated.
1652 if (!ForwardRefs.empty()) {
1653 nl(Out) << "// Resolve Forward References";
1654 nl(Out);
1655 }
1656
1657 while (!ForwardRefs.empty()) {
1658 ForwardRefMap::iterator I = ForwardRefs.begin();
1659 Out << I->second << "->replaceAllUsesWith("
1660 << getCppName(I->first) << "); delete " << I->second << ";";
1661 nl(Out);
1662 ForwardRefs.erase(I);
1663 }
1664}
1665
1666void CppWriter::printInline(const std::string& fname,
1667 const std::string& func) {
1668 const Function* F = TheModule->getFunction(func);
1669 if (!F) {
1670 error(std::string("Function '") + func + "' not found in input module");
1671 return;
1672 }
1673 if (F->isDeclaration()) {
1674 error(std::string("Function '") + func + "' is external!");
1675 return;
1676 }
1677 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1678 << getCppName(F);
1679 unsigned arg_count = 1;
1680 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1681 AI != AE; ++AI) {
1682 Out << ", Value* arg_" << arg_count;
1683 }
1684 Out << ") {";
1685 nl(Out);
1686 is_inline = true;
1687 printFunctionUses(F);
1688 printFunctionBody(F);
1689 is_inline = false;
1690 Out << "return " << getCppName(F->begin()) << ";";
1691 nl(Out) << "}";
1692 nl(Out);
1693}
1694
1695void CppWriter::printModuleBody() {
1696 // Print out all the type definitions
1697 nl(Out) << "// Type Definitions"; nl(Out);
1698 printTypes(TheModule);
1699
1700 // Functions can call each other and global variables can reference them so
1701 // define all the functions first before emitting their function bodies.
1702 nl(Out) << "// Function Declarations"; nl(Out);
1703 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1704 I != E; ++I)
1705 printFunctionHead(I);
1706
1707 // Process the global variables declarations. We can't initialze them until
1708 // after the constants are printed so just print a header for each global
1709 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1710 for (Module::const_global_iterator I = TheModule->global_begin(),
1711 E = TheModule->global_end(); I != E; ++I) {
1712 printVariableHead(I);
1713 }
1714
1715 // Print out all the constants definitions. Constants don't recurse except
1716 // through GlobalValues. All GlobalValues have been declared at this point
1717 // so we can proceed to generate the constants.
1718 nl(Out) << "// Constant Definitions"; nl(Out);
1719 printConstants(TheModule);
1720
1721 // Process the global variables definitions now that all the constants have
1722 // been emitted. These definitions just couple the gvars with their constant
1723 // initializers.
1724 nl(Out) << "// Global Variable Definitions"; nl(Out);
1725 for (Module::const_global_iterator I = TheModule->global_begin(),
1726 E = TheModule->global_end(); I != E; ++I) {
1727 printVariableBody(I);
1728 }
1729
1730 // Finally, we can safely put out all of the function bodies.
1731 nl(Out) << "// Function Definitions"; nl(Out);
1732 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1733 I != E; ++I) {
1734 if (!I->isDeclaration()) {
1735 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1736 << ")";
1737 nl(Out) << "{";
1738 nl(Out,1);
1739 printFunctionBody(I);
1740 nl(Out,-1) << "}";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001741 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001742 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001743 }
1744}
1745
1746void CppWriter::printProgram(const std::string& fname,
1747 const std::string& mName) {
1748 Out << "#include <llvm/LLVMContext.h>\n";
1749 Out << "#include <llvm/Module.h>\n";
1750 Out << "#include <llvm/DerivedTypes.h>\n";
1751 Out << "#include <llvm/Constants.h>\n";
1752 Out << "#include <llvm/GlobalVariable.h>\n";
1753 Out << "#include <llvm/Function.h>\n";
1754 Out << "#include <llvm/CallingConv.h>\n";
1755 Out << "#include <llvm/BasicBlock.h>\n";
1756 Out << "#include <llvm/Instructions.h>\n";
1757 Out << "#include <llvm/InlineAsm.h>\n";
1758 Out << "#include <llvm/Support/FormattedStream.h>\n";
1759 Out << "#include <llvm/Support/MathExtras.h>\n";
1760 Out << "#include <llvm/Pass.h>\n";
1761 Out << "#include <llvm/PassManager.h>\n";
1762 Out << "#include <llvm/ADT/SmallVector.h>\n";
1763 Out << "#include <llvm/Analysis/Verifier.h>\n";
1764 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1765 Out << "#include <algorithm>\n";
1766 Out << "using namespace llvm;\n\n";
1767 Out << "Module* " << fname << "();\n\n";
1768 Out << "int main(int argc, char**argv) {\n";
1769 Out << " Module* Mod = " << fname << "();\n";
1770 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1771 Out << " PassManager PM;\n";
1772 Out << " PM.add(createPrintModulePass(&outs()));\n";
1773 Out << " PM.run(*Mod);\n";
1774 Out << " return 0;\n";
1775 Out << "}\n\n";
1776 printModule(fname,mName);
1777}
1778
1779void CppWriter::printModule(const std::string& fname,
1780 const std::string& mName) {
1781 nl(Out) << "Module* " << fname << "() {";
1782 nl(Out,1) << "// Module Construction";
1783 nl(Out) << "Module* mod = new Module(\"";
1784 printEscapedString(mName);
1785 Out << "\", getGlobalContext());";
1786 if (!TheModule->getTargetTriple().empty()) {
1787 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1788 }
1789 if (!TheModule->getTargetTriple().empty()) {
1790 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1791 << "\");";
1792 }
1793
1794 if (!TheModule->getModuleInlineAsm().empty()) {
1795 nl(Out) << "mod->setModuleInlineAsm(\"";
1796 printEscapedString(TheModule->getModuleInlineAsm());
1797 Out << "\");";
1798 }
1799 nl(Out);
1800
1801 // Loop over the dependent libraries and emit them.
1802 Module::lib_iterator LI = TheModule->lib_begin();
1803 Module::lib_iterator LE = TheModule->lib_end();
1804 while (LI != LE) {
1805 Out << "mod->addLibrary(\"" << *LI << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001806 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001807 ++LI;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001808 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001809 printModuleBody();
1810 nl(Out) << "return mod;";
1811 nl(Out,-1) << "}";
1812 nl(Out);
1813}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001814
Chris Lattner7e6d7452010-06-21 23:12:56 +00001815void CppWriter::printContents(const std::string& fname,
1816 const std::string& mName) {
1817 Out << "\nModule* " << fname << "(Module *mod) {\n";
1818 Out << "\nmod->setModuleIdentifier(\"";
1819 printEscapedString(mName);
1820 Out << "\");\n";
1821 printModuleBody();
1822 Out << "\nreturn mod;\n";
1823 Out << "\n}\n";
1824}
1825
1826void CppWriter::printFunction(const std::string& fname,
1827 const std::string& funcName) {
1828 const Function* F = TheModule->getFunction(funcName);
1829 if (!F) {
1830 error(std::string("Function '") + funcName + "' not found in input module");
1831 return;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001832 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001833 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1834 printFunctionUses(F);
1835 printFunctionHead(F);
1836 printFunctionBody(F);
1837 Out << "return " << getCppName(F) << ";\n";
1838 Out << "}\n";
1839}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001840
Chris Lattner7e6d7452010-06-21 23:12:56 +00001841void CppWriter::printFunctions() {
1842 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1843 Module::const_iterator I = funcs.begin();
1844 Module::const_iterator IE = funcs.end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001845
Chris Lattner7e6d7452010-06-21 23:12:56 +00001846 for (; I != IE; ++I) {
1847 const Function &func = *I;
1848 if (!func.isDeclaration()) {
1849 std::string name("define_");
1850 name += func.getName();
1851 printFunction(name, func.getName());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001852 }
1853 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001854}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001855
Chris Lattner7e6d7452010-06-21 23:12:56 +00001856void CppWriter::printVariable(const std::string& fname,
1857 const std::string& varName) {
1858 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001859
Chris Lattner7e6d7452010-06-21 23:12:56 +00001860 if (!GV) {
1861 error(std::string("Variable '") + varName + "' not found in input module");
1862 return;
1863 }
1864 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1865 printVariableUses(GV);
1866 printVariableHead(GV);
1867 printVariableBody(GV);
1868 Out << "return " << getCppName(GV) << ";\n";
1869 Out << "}\n";
1870}
1871
Chris Lattner1afcace2011-07-09 17:41:24 +00001872void CppWriter::printType(const std::string &fname,
1873 const std::string &typeName) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001874 Type* Ty = TheModule->getTypeByName(typeName);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001875 if (!Ty) {
1876 error(std::string("Type '") + typeName + "' not found in input module");
1877 return;
1878 }
1879 Out << "\nType* " << fname << "(Module *mod) {\n";
1880 printType(Ty);
1881 Out << "return " << getCppName(Ty) << ";\n";
1882 Out << "}\n";
1883}
1884
1885bool CppWriter::runOnModule(Module &M) {
1886 TheModule = &M;
1887
1888 // Emit a header
1889 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1890
1891 // Get the name of the function we're supposed to generate
1892 std::string fname = FuncName.getValue();
1893
1894 // Get the name of the thing we are to generate
1895 std::string tgtname = NameToGenerate.getValue();
1896 if (GenerationType == GenModule ||
1897 GenerationType == GenContents ||
1898 GenerationType == GenProgram ||
1899 GenerationType == GenFunctions) {
1900 if (tgtname == "!bad!") {
1901 if (M.getModuleIdentifier() == "-")
1902 tgtname = "<stdin>";
1903 else
1904 tgtname = M.getModuleIdentifier();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001905 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001906 } else if (tgtname == "!bad!")
1907 error("You must use the -for option with -gen-{function,variable,type}");
1908
1909 switch (WhatToGenerate(GenerationType)) {
1910 case GenProgram:
1911 if (fname.empty())
1912 fname = "makeLLVMModule";
1913 printProgram(fname,tgtname);
1914 break;
1915 case GenModule:
1916 if (fname.empty())
1917 fname = "makeLLVMModule";
1918 printModule(fname,tgtname);
1919 break;
1920 case GenContents:
1921 if (fname.empty())
1922 fname = "makeLLVMModuleContents";
1923 printContents(fname,tgtname);
1924 break;
1925 case GenFunction:
1926 if (fname.empty())
1927 fname = "makeLLVMFunction";
1928 printFunction(fname,tgtname);
1929 break;
1930 case GenFunctions:
1931 printFunctions();
1932 break;
1933 case GenInline:
1934 if (fname.empty())
1935 fname = "makeLLVMInline";
1936 printInline(fname,tgtname);
1937 break;
1938 case GenVariable:
1939 if (fname.empty())
1940 fname = "makeLLVMVariable";
1941 printVariable(fname,tgtname);
1942 break;
1943 case GenType:
1944 if (fname.empty())
1945 fname = "makeLLVMType";
1946 printType(fname,tgtname);
1947 break;
1948 default:
1949 error("Invalid generation option");
Anton Korobeynikov50276522008-04-23 22:29:24 +00001950 }
1951
Chris Lattner7e6d7452010-06-21 23:12:56 +00001952 return false;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001953}
1954
1955char CppWriter::ID = 0;
1956
1957//===----------------------------------------------------------------------===//
1958// External Interface declaration
1959//===----------------------------------------------------------------------===//
1960
Dan Gohman99dca4f2010-05-11 19:57:55 +00001961bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
1962 formatted_raw_ostream &o,
1963 CodeGenFileType FileType,
1964 CodeGenOpt::Level OptLevel,
1965 bool DisableVerify) {
Chris Lattner211edae2010-02-02 21:06:45 +00001966 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001967 PM.add(new CppWriter(o));
1968 return false;
1969}