blob: 45a0c84a4f0164625fea43bd6bb352e4d04768c6 [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"
25#include "llvm/TypeSymbolTable.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000026#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/Support/CommandLine.h"
Torok Edwin30464702009-07-08 20:55:50 +000028#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000029#include "llvm/Support/FormattedStream.h"
Daniel Dunbar0c795d62009-07-25 06:49:55 +000030#include "llvm/Target/TargetRegistry.h"
Chris Lattner23132b12009-08-24 03:52:50 +000031#include "llvm/ADT/StringExtras.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000032#include "llvm/Config/config.h"
33#include <algorithm>
Anton Korobeynikov50276522008-04-23 22:29:24 +000034#include <set>
35
36using namespace llvm;
37
38static cl::opt<std::string>
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000039FuncName("cppfname", cl::desc("Specify the name of the generated function"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000040 cl::value_desc("function name"));
41
42enum WhatToGenerate {
43 GenProgram,
44 GenModule,
45 GenContents,
46 GenFunction,
47 GenFunctions,
48 GenInline,
49 GenVariable,
50 GenType
51};
52
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000053static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000054 cl::desc("Choose what kind of output to generate"),
55 cl::init(GenProgram),
56 cl::values(
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000057 clEnumValN(GenProgram, "program", "Generate a complete program"),
58 clEnumValN(GenModule, "module", "Generate a module definition"),
59 clEnumValN(GenContents, "contents", "Generate contents of a module"),
60 clEnumValN(GenFunction, "function", "Generate a function definition"),
61 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
62 clEnumValN(GenInline, "inline", "Generate an inline function"),
63 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
64 clEnumValN(GenType, "type", "Generate a type definition"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000065 clEnumValEnd
66 )
67);
68
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000069static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000070 cl::desc("Specify the name of the thing to generate"),
71 cl::init("!bad!"));
72
Daniel Dunbar0c795d62009-07-25 06:49:55 +000073extern "C" void LLVMInitializeCppBackendTarget() {
74 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000075 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000076}
Douglas Gregor1555a232009-06-16 20:12:29 +000077
Dan Gohman844731a2008-05-13 00:00:25 +000078namespace {
Anton Korobeynikov50276522008-04-23 22:29:24 +000079 typedef std::vector<const Type*> TypeList;
80 typedef std::map<const Type*,std::string> TypeMap;
81 typedef std::map<const Value*,std::string> ValueMap;
82 typedef std::set<std::string> NameSet;
83 typedef std::set<const Type*> TypeSet;
84 typedef std::set<const Value*> ValueSet;
85 typedef std::map<const Value*,std::string> ForwardRefMap;
86
87 /// CppWriter - This class is the main chunk of code that converts an LLVM
88 /// module to a C++ translation unit.
89 class CppWriter : public ModulePass {
David Greene71847812009-07-14 20:18:05 +000090 formatted_raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +000091 const Module *TheModule;
92 uint64_t uniqueNum;
93 TypeMap TypeNames;
94 ValueMap ValueNames;
95 TypeMap UnresolvedTypes;
96 TypeList TypeStack;
97 NameSet UsedNames;
98 TypeSet DefinedTypes;
99 ValueSet DefinedValues;
100 ForwardRefMap ForwardRefs;
101 bool is_inline;
102
103 public:
104 static char ID;
David Greene71847812009-07-14 20:18:05 +0000105 explicit CppWriter(formatted_raw_ostream &o) :
Dan Gohmanae73dc12008-09-04 17:05:41 +0000106 ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000107
108 virtual const char *getPassName() const { return "C++ backend"; }
109
110 bool runOnModule(Module &M);
111
Anton Korobeynikov50276522008-04-23 22:29:24 +0000112 void printProgram(const std::string& fname, const std::string& modName );
113 void printModule(const std::string& fname, const std::string& modName );
114 void printContents(const std::string& fname, const std::string& modName );
115 void printFunction(const std::string& fname, const std::string& funcName );
116 void printFunctions();
117 void printInline(const std::string& fname, const std::string& funcName );
118 void printVariable(const std::string& fname, const std::string& varName );
119 void printType(const std::string& fname, const std::string& typeName );
120
121 void error(const std::string& msg);
122
123 private:
124 void printLinkageType(GlobalValue::LinkageTypes LT);
125 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000126 void printCallingConv(CallingConv::ID cc);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000127 void printEscapedString(const std::string& str);
128 void printCFP(const ConstantFP* CFP);
129
130 std::string getCppName(const Type* val);
131 inline void printCppName(const Type* val);
132
133 std::string getCppName(const Value* val);
134 inline void printCppName(const Value* val);
135
Devang Patel05988662008-09-25 21:00:45 +0000136 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000137 bool printTypeInternal(const Type* Ty);
138 inline void printType(const Type* Ty);
139 void printTypes(const Module* M);
140
141 void printConstant(const Constant *CPV);
142 void printConstants(const Module* M);
143
144 void printVariableUses(const GlobalVariable *GV);
145 void printVariableHead(const GlobalVariable *GV);
146 void printVariableBody(const GlobalVariable *GV);
147
148 void printFunctionUses(const Function *F);
149 void printFunctionHead(const Function *F);
150 void printFunctionBody(const Function *F);
151 void printInstruction(const Instruction *I, const std::string& bbname);
152 std::string getOpName(Value*);
153
154 void printModuleBody();
155 };
156
157 static unsigned indent_level = 0;
David Greene71847812009-07-14 20:18:05 +0000158 inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000159 Out << "\n";
160 if (delta >= 0 || indent_level >= unsigned(-delta))
161 indent_level += delta;
162 for (unsigned i = 0; i < indent_level; ++i)
163 Out << " ";
164 return Out;
165 }
166
167 inline void in() { indent_level++; }
168 inline void out() { if (indent_level >0) indent_level--; }
169
170 inline void
171 sanitize(std::string& str) {
172 for (size_t i = 0; i < str.length(); ++i)
173 if (!isalnum(str[i]) && str[i] != '_')
174 str[i] = '_';
175 }
176
177 inline std::string
178 getTypePrefix(const Type* Ty ) {
179 switch (Ty->getTypeID()) {
180 case Type::VoidTyID: return "void_";
181 case Type::IntegerTyID:
182 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
183 "_";
184 case Type::FloatTyID: return "float_";
185 case Type::DoubleTyID: return "double_";
186 case Type::LabelTyID: return "label_";
187 case Type::FunctionTyID: return "func_";
188 case Type::StructTyID: return "struct_";
189 case Type::ArrayTyID: return "array_";
190 case Type::PointerTyID: return "ptr_";
191 case Type::VectorTyID: return "packed_";
192 case Type::OpaqueTyID: return "opaque_";
193 default: return "other_";
194 }
195 return "unknown_";
196 }
197
198 // Looks up the type in the symbol table and returns a pointer to its name or
199 // a null pointer if it wasn't found. Note that this isn't the same as the
200 // Mode::getTypeName function which will return an empty string, not a null
201 // pointer if the name is not found.
202 inline const std::string*
203 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
204 TypeSymbolTable::const_iterator TI = ST.begin();
205 TypeSymbolTable::const_iterator TE = ST.end();
206 for (;TI != TE; ++TI)
207 if (TI->second == Ty)
208 return &(TI->first);
209 return 0;
210 }
211
212 void CppWriter::error(const std::string& msg) {
Chris Lattner75361b62010-04-07 22:58:41 +0000213 report_fatal_error(msg);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000214 }
215
216 // printCFP - Print a floating point constant .. very carefully :)
217 // This makes sure that conversion to/from floating yields the same binary
218 // result so that we don't lose precision.
219 void CppWriter::printCFP(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000220 bool ignored;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000221 APFloat APF = APFloat(CFP->getValueAPF()); // copy
Owen Anderson1d0be152009-08-13 21:58:54 +0000222 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
Dale Johannesen23a98552008-10-09 23:00:39 +0000223 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Nicolas Geoffray81d97c02010-02-23 19:42:44 +0000224 Out << "ConstantFP::get(mod->getContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000225 Out << "APFloat(";
226#if HAVE_PRINTF_A
227 char Buffer[100];
228 sprintf(Buffer, "%A", APF.convertToDouble());
229 if ((!strncmp(Buffer, "0x", 2) ||
230 !strncmp(Buffer, "-0x", 3) ||
231 !strncmp(Buffer, "+0x", 3)) &&
232 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000233 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
Anton Korobeynikov50276522008-04-23 22:29:24 +0000234 Out << "BitsToDouble(" << Buffer << ")";
235 else
236 Out << "BitsToFloat((float)" << Buffer << ")";
237 Out << ")";
238 } else {
239#endif
240 std::string StrVal = ftostr(CFP->getValueAPF());
241
242 while (StrVal[0] == ' ')
243 StrVal.erase(StrVal.begin());
244
245 // Check to make sure that the stringized number is not some string like
246 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
247 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
248 ((StrVal[0] == '-' || StrVal[0] == '+') &&
249 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
250 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000251 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
Anton Korobeynikov50276522008-04-23 22:29:24 +0000252 Out << StrVal;
253 else
254 Out << StrVal << "f";
Owen Anderson1d0be152009-08-13 21:58:54 +0000255 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
Owen Andersoncb371882008-08-21 00:14:44 +0000256 Out << "BitsToDouble(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000257 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000258 << "ULL) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000259 else
Owen Andersoncb371882008-08-21 00:14:44 +0000260 Out << "BitsToFloat(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000261 << utohexstr((uint32_t)CFP->getValueAPF().
262 bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000263 << "U) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000264 Out << ")";
265#if HAVE_PRINTF_A
266 }
267#endif
268 Out << ")";
269 }
270
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000271 void CppWriter::printCallingConv(CallingConv::ID cc){
Anton Korobeynikov50276522008-04-23 22:29:24 +0000272 // Print the calling convention.
273 switch (cc) {
274 case CallingConv::C: Out << "CallingConv::C"; break;
275 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
276 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
277 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
278 default: Out << cc; break;
279 }
280 }
281
282 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
283 switch (LT) {
284 case GlobalValue::InternalLinkage:
285 Out << "GlobalValue::InternalLinkage"; break;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000286 case GlobalValue::PrivateLinkage:
287 Out << "GlobalValue::PrivateLinkage"; break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000288 case GlobalValue::LinkerPrivateLinkage:
289 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000290 case GlobalValue::AvailableExternallyLinkage:
291 Out << "GlobalValue::AvailableExternallyLinkage "; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000292 case GlobalValue::LinkOnceAnyLinkage:
293 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
294 case GlobalValue::LinkOnceODRLinkage:
295 Out << "GlobalValue::LinkOnceODRLinkage "; break;
296 case GlobalValue::WeakAnyLinkage:
297 Out << "GlobalValue::WeakAnyLinkage"; break;
298 case GlobalValue::WeakODRLinkage:
299 Out << "GlobalValue::WeakODRLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000300 case GlobalValue::AppendingLinkage:
301 Out << "GlobalValue::AppendingLinkage"; break;
302 case GlobalValue::ExternalLinkage:
303 Out << "GlobalValue::ExternalLinkage"; break;
304 case GlobalValue::DLLImportLinkage:
305 Out << "GlobalValue::DLLImportLinkage"; break;
306 case GlobalValue::DLLExportLinkage:
307 Out << "GlobalValue::DLLExportLinkage"; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000308 case GlobalValue::ExternalWeakLinkage:
309 Out << "GlobalValue::ExternalWeakLinkage"; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000310 case GlobalValue::CommonLinkage:
311 Out << "GlobalValue::CommonLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000312 }
313 }
314
315 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
316 switch (VisType) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000317 default: llvm_unreachable("Unknown GVar visibility");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000318 case GlobalValue::DefaultVisibility:
319 Out << "GlobalValue::DefaultVisibility";
320 break;
321 case GlobalValue::HiddenVisibility:
322 Out << "GlobalValue::HiddenVisibility";
323 break;
324 case GlobalValue::ProtectedVisibility:
325 Out << "GlobalValue::ProtectedVisibility";
326 break;
327 }
328 }
329
330 // printEscapedString - Print each character of the specified string, escaping
331 // it if it is not printable or if it is an escape char.
332 void CppWriter::printEscapedString(const std::string &Str) {
333 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
334 unsigned char C = Str[i];
335 if (isprint(C) && C != '"' && C != '\\') {
336 Out << C;
337 } else {
338 Out << "\\x"
339 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
340 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
341 }
342 }
343 }
344
345 std::string CppWriter::getCppName(const Type* Ty) {
346 // First, handle the primitive types .. easy
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000347 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000348 switch (Ty->getTypeID()) {
Nicolas Geoffray81d97c02010-02-23 19:42:44 +0000349 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000350 case Type::IntegerTyID: {
351 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
Nicolas Geoffray81d97c02010-02-23 19:42:44 +0000352 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000353 }
Nicolas Geoffray81d97c02010-02-23 19:42:44 +0000354 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
355 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
356 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
357 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000358 default:
359 error("Invalid primitive type");
360 break;
361 }
Nicolas Geoffrayab2a6632009-08-15 14:47:42 +0000362 // shouldn't be returned, but make it sensible
Nicolas Geoffray81d97c02010-02-23 19:42:44 +0000363 return "Type::getVoidTy(mod->getContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000364 }
365
366 // Now, see if we've seen the type before and return that
367 TypeMap::iterator I = TypeNames.find(Ty);
368 if (I != TypeNames.end())
369 return I->second;
370
371 // Okay, let's build a new name for this type. Start with a prefix
372 const char* prefix = 0;
373 switch (Ty->getTypeID()) {
374 case Type::FunctionTyID: prefix = "FuncTy_"; break;
375 case Type::StructTyID: prefix = "StructTy_"; break;
376 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
377 case Type::PointerTyID: prefix = "PointerTy_"; break;
378 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
379 case Type::VectorTyID: prefix = "VectorTy_"; break;
380 default: prefix = "OtherTy_"; break; // prevent breakage
381 }
382
383 // See if the type has a name in the symboltable and build accordingly
384 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
385 std::string name;
386 if (tName)
387 name = std::string(prefix) + *tName;
388 else
389 name = std::string(prefix) + utostr(uniqueNum++);
390 sanitize(name);
391
392 // Save the name
393 return TypeNames[Ty] = name;
394 }
395
396 void CppWriter::printCppName(const Type* Ty) {
397 printEscapedString(getCppName(Ty));
398 }
399
400 std::string CppWriter::getCppName(const Value* val) {
401 std::string name;
402 ValueMap::iterator I = ValueNames.find(val);
403 if (I != ValueNames.end() && I->first == val)
404 return I->second;
405
406 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
407 name = std::string("gvar_") +
408 getTypePrefix(GV->getType()->getElementType());
409 } else if (isa<Function>(val)) {
410 name = std::string("func_");
411 } else if (const Constant* C = dyn_cast<Constant>(val)) {
412 name = std::string("const_") + getTypePrefix(C->getType());
413 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
414 if (is_inline) {
415 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
416 Function::const_arg_iterator(Arg)) + 1;
417 name = std::string("arg_") + utostr(argNum);
418 NameSet::iterator NI = UsedNames.find(name);
419 if (NI != UsedNames.end())
420 name += std::string("_") + utostr(uniqueNum++);
421 UsedNames.insert(name);
422 return ValueNames[val] = name;
423 } else {
424 name = getTypePrefix(val->getType());
425 }
426 } else {
427 name = getTypePrefix(val->getType());
428 }
Daniel Dunbar8f603022009-07-22 21:10:12 +0000429 if (val->hasName())
430 name += val->getName();
431 else
432 name += utostr(uniqueNum++);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000433 sanitize(name);
434 NameSet::iterator NI = UsedNames.find(name);
435 if (NI != UsedNames.end())
436 name += std::string("_") + utostr(uniqueNum++);
437 UsedNames.insert(name);
438 return ValueNames[val] = name;
439 }
440
441 void CppWriter::printCppName(const Value* val) {
442 printEscapedString(getCppName(val));
443 }
444
Devang Patel05988662008-09-25 21:00:45 +0000445 void CppWriter::printAttributes(const AttrListPtr &PAL,
Anton Korobeynikov50276522008-04-23 22:29:24 +0000446 const std::string &name) {
Devang Patel05988662008-09-25 21:00:45 +0000447 Out << "AttrListPtr " << name << "_PAL;";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000448 nl(Out);
449 if (!PAL.isEmpty()) {
450 Out << '{'; in(); nl(Out);
Devang Patel05988662008-09-25 21:00:45 +0000451 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
452 Out << "AttributeWithIndex PAWI;"; nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000453 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000454 unsigned index = PAL.getSlot(i).Index;
Devang Pateleaf42ab2008-09-23 23:03:40 +0000455 Attributes attrs = PAL.getSlot(i).Attrs;
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000456 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
Chris Lattneracca9552009-01-13 07:22:22 +0000457#define HANDLE_ATTR(X) \
458 if (attrs & Attribute::X) \
459 Out << " | Attribute::" #X; \
460 attrs &= ~Attribute::X;
461
462 HANDLE_ATTR(SExt);
463 HANDLE_ATTR(ZExt);
Chris Lattneracca9552009-01-13 07:22:22 +0000464 HANDLE_ATTR(NoReturn);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000465 HANDLE_ATTR(InReg);
466 HANDLE_ATTR(StructRet);
Chris Lattneracca9552009-01-13 07:22:22 +0000467 HANDLE_ATTR(NoUnwind);
Chris Lattneracca9552009-01-13 07:22:22 +0000468 HANDLE_ATTR(NoAlias);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000469 HANDLE_ATTR(ByVal);
Chris Lattneracca9552009-01-13 07:22:22 +0000470 HANDLE_ATTR(Nest);
471 HANDLE_ATTR(ReadNone);
472 HANDLE_ATTR(ReadOnly);
Jakob Stoklund Olesen570a4a52010-02-06 01:16:28 +0000473 HANDLE_ATTR(InlineHint);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000474 HANDLE_ATTR(NoInline);
475 HANDLE_ATTR(AlwaysInline);
476 HANDLE_ATTR(OptimizeForSize);
477 HANDLE_ATTR(StackProtect);
478 HANDLE_ATTR(StackProtectReq);
Chris Lattneracca9552009-01-13 07:22:22 +0000479 HANDLE_ATTR(NoCapture);
480#undef HANDLE_ATTR
481 assert(attrs == 0 && "Unhandled attribute!");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000482 Out << ";";
483 nl(Out);
484 Out << "Attrs.push_back(PAWI);";
485 nl(Out);
486 }
Devang Patel05988662008-09-25 21:00:45 +0000487 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000488 nl(Out);
489 out(); nl(Out);
490 Out << '}'; nl(Out);
491 }
492 }
493
494 bool CppWriter::printTypeInternal(const Type* Ty) {
495 // We don't print definitions for primitive types
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000496 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
Anton Korobeynikov50276522008-04-23 22:29:24 +0000497 return false;
498
499 // If we already defined this type, we don't need to define it again.
500 if (DefinedTypes.find(Ty) != DefinedTypes.end())
501 return false;
502
503 // Everything below needs the name for the type so get it now.
504 std::string typeName(getCppName(Ty));
505
506 // Search the type stack for recursion. If we find it, then generate this
507 // as an OpaqueType, but make sure not to do this multiple times because
508 // the type could appear in multiple places on the stack. Once the opaque
509 // definition is issued, it must not be re-issued. Consequently we have to
510 // check the UnresolvedTypes list as well.
511 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
512 Ty);
513 if (TI != TypeStack.end()) {
514 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
515 if (I == UnresolvedTypes.end()) {
Nicolas Geoffraybad9def2009-08-15 15:41:32 +0000516 Out << "PATypeHolder " << typeName;
Nicolas Geoffray81d97c02010-02-23 19:42:44 +0000517 Out << "_fwd = OpaqueType::get(mod->getContext());";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000518 nl(Out);
519 UnresolvedTypes[Ty] = typeName;
520 }
521 return true;
522 }
523
524 // We're going to print a derived type which, by definition, contains other
525 // types. So, push this one we're printing onto the type stack to assist with
526 // recursive definitions.
527 TypeStack.push_back(Ty);
528
529 // Print the type definition
530 switch (Ty->getTypeID()) {
531 case Type::FunctionTyID: {
532 const FunctionType* FT = cast<FunctionType>(Ty);
533 Out << "std::vector<const Type*>" << typeName << "_args;";
534 nl(Out);
535 FunctionType::param_iterator PI = FT->param_begin();
536 FunctionType::param_iterator PE = FT->param_end();
537 for (; PI != PE; ++PI) {
538 const Type* argTy = static_cast<const Type*>(*PI);
539 bool isForward = printTypeInternal(argTy);
540 std::string argName(getCppName(argTy));
541 Out << typeName << "_args.push_back(" << argName;
542 if (isForward)
543 Out << "_fwd";
544 Out << ");";
545 nl(Out);
546 }
547 bool isForward = printTypeInternal(FT->getReturnType());
548 std::string retTypeName(getCppName(FT->getReturnType()));
549 Out << "FunctionType* " << typeName << " = FunctionType::get(";
550 in(); nl(Out) << "/*Result=*/" << retTypeName;
551 if (isForward)
552 Out << "_fwd";
553 Out << ",";
554 nl(Out) << "/*Params=*/" << typeName << "_args,";
555 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
556 out();
557 nl(Out);
558 break;
559 }
560 case Type::StructTyID: {
561 const StructType* ST = cast<StructType>(Ty);
562 Out << "std::vector<const Type*>" << typeName << "_fields;";
563 nl(Out);
564 StructType::element_iterator EI = ST->element_begin();
565 StructType::element_iterator EE = ST->element_end();
566 for (; EI != EE; ++EI) {
567 const Type* fieldTy = static_cast<const Type*>(*EI);
568 bool isForward = printTypeInternal(fieldTy);
569 std::string fieldName(getCppName(fieldTy));
570 Out << typeName << "_fields.push_back(" << fieldName;
571 if (isForward)
572 Out << "_fwd";
573 Out << ");";
574 nl(Out);
575 }
576 Out << "StructType* " << typeName << " = StructType::get("
Nicolas Geoffray6f62cff2009-08-06 21:31:35 +0000577 << "mod->getContext(), "
Anton Korobeynikov50276522008-04-23 22:29:24 +0000578 << typeName << "_fields, /*isPacked=*/"
579 << (ST->isPacked() ? "true" : "false") << ");";
580 nl(Out);
581 break;
582 }
583 case Type::ArrayTyID: {
584 const ArrayType* AT = cast<ArrayType>(Ty);
585 const Type* ET = AT->getElementType();
586 bool isForward = printTypeInternal(ET);
587 std::string elemName(getCppName(ET));
588 Out << "ArrayType* " << typeName << " = ArrayType::get("
589 << elemName << (isForward ? "_fwd" : "")
590 << ", " << utostr(AT->getNumElements()) << ");";
591 nl(Out);
592 break;
593 }
594 case Type::PointerTyID: {
595 const PointerType* PT = cast<PointerType>(Ty);
596 const Type* ET = PT->getElementType();
597 bool isForward = printTypeInternal(ET);
598 std::string elemName(getCppName(ET));
599 Out << "PointerType* " << typeName << " = PointerType::get("
600 << elemName << (isForward ? "_fwd" : "")
601 << ", " << utostr(PT->getAddressSpace()) << ");";
602 nl(Out);
603 break;
604 }
605 case Type::VectorTyID: {
606 const VectorType* PT = cast<VectorType>(Ty);
607 const Type* ET = PT->getElementType();
608 bool isForward = printTypeInternal(ET);
609 std::string elemName(getCppName(ET));
610 Out << "VectorType* " << typeName << " = VectorType::get("
611 << elemName << (isForward ? "_fwd" : "")
612 << ", " << utostr(PT->getNumElements()) << ");";
613 nl(Out);
614 break;
615 }
616 case Type::OpaqueTyID: {
Nicolas Geoffraybad9def2009-08-15 15:41:32 +0000617 Out << "OpaqueType* " << typeName;
Nicolas Geoffray81d97c02010-02-23 19:42:44 +0000618 Out << " = OpaqueType::get(mod->getContext());";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000619 nl(Out);
620 break;
621 }
622 default:
623 error("Invalid TypeID");
624 }
625
626 // If the type had a name, make sure we recreate it.
627 const std::string* progTypeName =
628 findTypeName(TheModule->getTypeSymbolTable(),Ty);
629 if (progTypeName) {
630 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
631 << typeName << ");";
632 nl(Out);
633 }
634
635 // Pop us off the type stack
636 TypeStack.pop_back();
637
638 // Indicate that this type is now defined.
639 DefinedTypes.insert(Ty);
640
641 // Early resolve as many unresolved types as possible. Search the unresolved
642 // types map for the type we just printed. Now that its definition is complete
643 // we can resolve any previous references to it. This prevents a cascade of
644 // unresolved types.
645 TypeMap::iterator I = UnresolvedTypes.find(Ty);
646 if (I != UnresolvedTypes.end()) {
647 Out << "cast<OpaqueType>(" << I->second
648 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
649 nl(Out);
650 Out << I->second << " = cast<";
651 switch (Ty->getTypeID()) {
652 case Type::FunctionTyID: Out << "FunctionType"; break;
653 case Type::ArrayTyID: Out << "ArrayType"; break;
654 case Type::StructTyID: Out << "StructType"; break;
655 case Type::VectorTyID: Out << "VectorType"; break;
656 case Type::PointerTyID: Out << "PointerType"; break;
657 case Type::OpaqueTyID: Out << "OpaqueType"; break;
658 default: Out << "NoSuchDerivedType"; break;
659 }
660 Out << ">(" << I->second << "_fwd.get());";
661 nl(Out); nl(Out);
662 UnresolvedTypes.erase(I);
663 }
664
665 // Finally, separate the type definition from other with a newline.
666 nl(Out);
667
668 // We weren't a recursive type
669 return false;
670 }
671
672 // Prints a type definition. Returns true if it could not resolve all the
673 // types in the definition but had to use a forward reference.
674 void CppWriter::printType(const Type* Ty) {
675 assert(TypeStack.empty());
676 TypeStack.clear();
677 printTypeInternal(Ty);
678 assert(TypeStack.empty());
679 }
680
681 void CppWriter::printTypes(const Module* M) {
682 // Walk the symbol table and print out all its types
683 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
684 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
685 TI != TE; ++TI) {
686
687 // For primitive types and types already defined, just add a name
688 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000689 if (TI->second->isIntegerTy() || TI->second->isPrimitiveType() ||
Anton Korobeynikov50276522008-04-23 22:29:24 +0000690 TNI != TypeNames.end()) {
691 Out << "mod->addTypeName(\"";
692 printEscapedString(TI->first);
693 Out << "\", " << getCppName(TI->second) << ");";
694 nl(Out);
695 // For everything else, define the type
696 } else {
697 printType(TI->second);
698 }
699 }
700
701 // Add all of the global variables to the value table...
702 for (Module::const_global_iterator I = TheModule->global_begin(),
703 E = TheModule->global_end(); I != E; ++I) {
704 if (I->hasInitializer())
705 printType(I->getInitializer()->getType());
706 printType(I->getType());
707 }
708
709 // Add all the functions to the table
710 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
711 FI != FE; ++FI) {
712 printType(FI->getReturnType());
713 printType(FI->getFunctionType());
714 // Add all the function arguments
715 for (Function::const_arg_iterator AI = FI->arg_begin(),
716 AE = FI->arg_end(); AI != AE; ++AI) {
717 printType(AI->getType());
718 }
719
720 // Add all of the basic blocks and instructions
721 for (Function::const_iterator BB = FI->begin(),
722 E = FI->end(); BB != E; ++BB) {
723 printType(BB->getType());
724 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
725 ++I) {
726 printType(I->getType());
727 for (unsigned i = 0; i < I->getNumOperands(); ++i)
728 printType(I->getOperand(i)->getType());
729 }
730 }
731 }
732 }
733
734
735 // printConstant - Print out a constant pool entry...
736 void CppWriter::printConstant(const Constant *CV) {
737 // First, if the constant is actually a GlobalValue (variable or function)
738 // or its already in the constant list then we've printed it already and we
739 // can just return.
740 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
741 return;
742
743 std::string constName(getCppName(CV));
744 std::string typeName(getCppName(CV->getType()));
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000745
Anton Korobeynikov50276522008-04-23 22:29:24 +0000746 if (isa<GlobalValue>(CV)) {
747 // Skip variables and functions, we emit them elsewhere
748 return;
749 }
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000750
Anton Korobeynikov50276522008-04-23 22:29:24 +0000751 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Anton Korobeynikov70053c32008-08-18 20:03:45 +0000752 std::string constValue = CI->getValue().toString(10, true);
Owen Anderson267a0ff2009-08-14 17:41:33 +0000753 Out << "ConstantInt* " << constName
Nicolas Geoffray81d97c02010-02-23 19:42:44 +0000754 << " = ConstantInt::get(mod->getContext(), APInt("
Owen Anderson267a0ff2009-08-14 17:41:33 +0000755 << cast<IntegerType>(CI->getType())->getBitWidth()
Benjamin Kramer6d5f0f02009-09-03 14:58:24 +0000756 << ", StringRef(\"" << constValue << "\"), 10));";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000757 } else if (isa<ConstantAggregateZero>(CV)) {
758 Out << "ConstantAggregateZero* " << constName
759 << " = ConstantAggregateZero::get(" << typeName << ");";
760 } else if (isa<ConstantPointerNull>(CV)) {
761 Out << "ConstantPointerNull* " << constName
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000762 << " = ConstantPointerNull::get(" << typeName << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000763 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
764 Out << "ConstantFP* " << constName << " = ";
765 printCFP(CFP);
766 Out << ";";
767 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000768 if (CA->isString() &&
769 CA->getType()->getElementType() ==
770 Type::getInt8Ty(CA->getContext())) {
Owen Anderson267a0ff2009-08-14 17:41:33 +0000771 Out << "Constant* " << constName <<
Nicolas Geoffray81d97c02010-02-23 19:42:44 +0000772 " = ConstantArray::get(mod->getContext(), \"";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000773 std::string tmp = CA->getAsString();
774 bool nullTerminate = false;
775 if (tmp[tmp.length()-1] == 0) {
776 tmp.erase(tmp.length()-1);
777 nullTerminate = true;
778 }
779 printEscapedString(tmp);
780 // Determine if we want null termination or not.
781 if (nullTerminate)
782 Out << "\", true"; // Indicate that the null terminator should be
783 // added.
784 else
785 Out << "\", false";// No null terminator
786 Out << ");";
787 } else {
788 Out << "std::vector<Constant*> " << constName << "_elems;";
789 nl(Out);
790 unsigned N = CA->getNumOperands();
791 for (unsigned i = 0; i < N; ++i) {
792 printConstant(CA->getOperand(i)); // recurse to print operands
793 Out << constName << "_elems.push_back("
794 << getCppName(CA->getOperand(i)) << ");";
795 nl(Out);
796 }
797 Out << "Constant* " << constName << " = ConstantArray::get("
798 << typeName << ", " << constName << "_elems);";
799 }
800 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
801 Out << "std::vector<Constant*> " << constName << "_fields;";
802 nl(Out);
803 unsigned N = CS->getNumOperands();
804 for (unsigned i = 0; i < N; i++) {
805 printConstant(CS->getOperand(i));
806 Out << constName << "_fields.push_back("
807 << getCppName(CS->getOperand(i)) << ");";
808 nl(Out);
809 }
810 Out << "Constant* " << constName << " = ConstantStruct::get("
811 << typeName << ", " << constName << "_fields);";
812 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
813 Out << "std::vector<Constant*> " << constName << "_elems;";
814 nl(Out);
815 unsigned N = CP->getNumOperands();
816 for (unsigned i = 0; i < N; ++i) {
817 printConstant(CP->getOperand(i));
818 Out << constName << "_elems.push_back("
819 << getCppName(CP->getOperand(i)) << ");";
820 nl(Out);
821 }
822 Out << "Constant* " << constName << " = ConstantVector::get("
823 << typeName << ", " << constName << "_elems);";
824 } else if (isa<UndefValue>(CV)) {
825 Out << "UndefValue* " << constName << " = UndefValue::get("
826 << typeName << ");";
827 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
828 if (CE->getOpcode() == Instruction::GetElementPtr) {
829 Out << "std::vector<Constant*> " << constName << "_indices;";
830 nl(Out);
831 printConstant(CE->getOperand(0));
832 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
833 printConstant(CE->getOperand(i));
834 Out << constName << "_indices.push_back("
835 << getCppName(CE->getOperand(i)) << ");";
836 nl(Out);
837 }
838 Out << "Constant* " << constName
839 << " = ConstantExpr::getGetElementPtr("
840 << getCppName(CE->getOperand(0)) << ", "
841 << "&" << constName << "_indices[0], "
842 << constName << "_indices.size()"
Benjamin Kramer6d5f0f02009-09-03 14:58:24 +0000843 << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000844 } else if (CE->isCast()) {
845 printConstant(CE->getOperand(0));
846 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
847 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000848 default: llvm_unreachable("Invalid cast opcode");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000849 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
850 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
851 case Instruction::SExt: Out << "Instruction::SExt"; break;
852 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
853 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
854 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
855 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
856 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
857 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
858 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
859 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
860 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
861 }
862 Out << ", " << getCppName(CE->getOperand(0)) << ", "
863 << getCppName(CE->getType()) << ");";
864 } else {
865 unsigned N = CE->getNumOperands();
866 for (unsigned i = 0; i < N; ++i ) {
867 printConstant(CE->getOperand(i));
868 }
869 Out << "Constant* " << constName << " = ConstantExpr::";
870 switch (CE->getOpcode()) {
871 case Instruction::Add: Out << "getAdd("; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000872 case Instruction::FAdd: Out << "getFAdd("; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000873 case Instruction::Sub: Out << "getSub("; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000874 case Instruction::FSub: Out << "getFSub("; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000875 case Instruction::Mul: Out << "getMul("; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000876 case Instruction::FMul: Out << "getFMul("; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000877 case Instruction::UDiv: Out << "getUDiv("; break;
878 case Instruction::SDiv: Out << "getSDiv("; break;
879 case Instruction::FDiv: Out << "getFDiv("; break;
880 case Instruction::URem: Out << "getURem("; break;
881 case Instruction::SRem: Out << "getSRem("; break;
882 case Instruction::FRem: Out << "getFRem("; break;
883 case Instruction::And: Out << "getAnd("; break;
884 case Instruction::Or: Out << "getOr("; break;
885 case Instruction::Xor: Out << "getXor("; break;
886 case Instruction::ICmp:
887 Out << "getICmp(ICmpInst::ICMP_";
888 switch (CE->getPredicate()) {
889 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
890 case ICmpInst::ICMP_NE: Out << "NE"; break;
891 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
892 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
893 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
894 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
895 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
896 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
897 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
898 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
899 default: error("Invalid ICmp Predicate");
900 }
901 break;
902 case Instruction::FCmp:
903 Out << "getFCmp(FCmpInst::FCMP_";
904 switch (CE->getPredicate()) {
905 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
906 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
907 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
908 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
909 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
910 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
911 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
912 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
913 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
914 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
915 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
916 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
917 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
918 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
919 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
920 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
921 default: error("Invalid FCmp Predicate");
922 }
923 break;
924 case Instruction::Shl: Out << "getShl("; break;
925 case Instruction::LShr: Out << "getLShr("; break;
926 case Instruction::AShr: Out << "getAShr("; break;
927 case Instruction::Select: Out << "getSelect("; break;
928 case Instruction::ExtractElement: Out << "getExtractElement("; break;
929 case Instruction::InsertElement: Out << "getInsertElement("; break;
930 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
931 default:
932 error("Invalid constant expression");
933 break;
934 }
935 Out << getCppName(CE->getOperand(0));
936 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
937 Out << ", " << getCppName(CE->getOperand(i));
938 Out << ");";
939 }
940 } else {
941 error("Bad Constant");
942 Out << "Constant* " << constName << " = 0; ";
943 }
944 nl(Out);
945 }
946
947 void CppWriter::printConstants(const Module* M) {
948 // Traverse all the global variables looking for constant initializers
949 for (Module::const_global_iterator I = TheModule->global_begin(),
950 E = TheModule->global_end(); I != E; ++I)
951 if (I->hasInitializer())
952 printConstant(I->getInitializer());
953
954 // Traverse the LLVM functions looking for constants
955 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
956 FI != FE; ++FI) {
957 // Add all of the basic blocks and instructions
958 for (Function::const_iterator BB = FI->begin(),
959 E = FI->end(); BB != E; ++BB) {
960 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
961 ++I) {
962 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
963 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
964 printConstant(C);
965 }
966 }
967 }
968 }
969 }
970 }
971
972 void CppWriter::printVariableUses(const GlobalVariable *GV) {
973 nl(Out) << "// Type Definitions";
974 nl(Out);
975 printType(GV->getType());
976 if (GV->hasInitializer()) {
Chris Lattnercdfb3022009-12-14 19:34:32 +0000977 Constant *Init = GV->getInitializer();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000978 printType(Init->getType());
Chris Lattnercdfb3022009-12-14 19:34:32 +0000979 if (Function *F = dyn_cast<Function>(Init)) {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000980 nl(Out)<< "/ Function Declarations"; nl(Out);
981 printFunctionHead(F);
982 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
983 nl(Out) << "// Global Variable Declarations"; nl(Out);
984 printVariableHead(gv);
Chris Lattnercdfb3022009-12-14 19:34:32 +0000985
Anton Korobeynikov50276522008-04-23 22:29:24 +0000986 nl(Out) << "// Global Variable Definitions"; nl(Out);
987 printVariableBody(gv);
Chris Lattnercdfb3022009-12-14 19:34:32 +0000988 } else {
989 nl(Out) << "// Constant Definitions"; nl(Out);
990 printConstant(Init);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000991 }
992 }
993 }
994
995 void CppWriter::printVariableHead(const GlobalVariable *GV) {
996 nl(Out) << "GlobalVariable* " << getCppName(GV);
997 if (is_inline) {
Nicolas Geoffray81d97c02010-02-23 19:42:44 +0000998 Out << " = mod->getGlobalVariable(mod->getContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000999 printEscapedString(GV->getName());
1000 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
1001 nl(Out) << "if (!" << getCppName(GV) << ") {";
1002 in(); nl(Out) << getCppName(GV);
1003 }
Owen Anderson267a0ff2009-08-14 17:41:33 +00001004 Out << " = new GlobalVariable(/*Module=*/*mod, ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001005 nl(Out) << "/*Type=*/";
1006 printCppName(GV->getType()->getElementType());
1007 Out << ",";
1008 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1009 Out << ",";
1010 nl(Out) << "/*Linkage=*/";
1011 printLinkageType(GV->getLinkage());
1012 Out << ",";
1013 nl(Out) << "/*Initializer=*/0, ";
1014 if (GV->hasInitializer()) {
1015 Out << "// has initializer, specified below";
1016 }
1017 nl(Out) << "/*Name=*/\"";
1018 printEscapedString(GV->getName());
Owen Anderson16a412e2009-07-10 16:42:19 +00001019 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001020 nl(Out);
1021
1022 if (GV->hasSection()) {
1023 printCppName(GV);
1024 Out << "->setSection(\"";
1025 printEscapedString(GV->getSection());
1026 Out << "\");";
1027 nl(Out);
1028 }
1029 if (GV->getAlignment()) {
1030 printCppName(GV);
1031 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1032 nl(Out);
1033 }
1034 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1035 printCppName(GV);
1036 Out << "->setVisibility(";
1037 printVisibilityType(GV->getVisibility());
1038 Out << ");";
1039 nl(Out);
1040 }
Anton Korobeynikov61aeed12010-05-13 07:41:57 +00001041 if (GV->isThreadLocal()) {
1042 printCppName(GV);
1043 Out << "->setThreadLocal(true);";
1044 nl(Out);
1045 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001046 if (is_inline) {
1047 out(); Out << "}"; nl(Out);
1048 }
1049 }
1050
1051 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1052 if (GV->hasInitializer()) {
1053 printCppName(GV);
1054 Out << "->setInitializer(";
1055 Out << getCppName(GV->getInitializer()) << ");";
1056 nl(Out);
1057 }
1058 }
1059
1060 std::string CppWriter::getOpName(Value* V) {
1061 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1062 return getCppName(V);
1063
1064 // See if its alread in the map of forward references, if so just return the
1065 // name we already set up for it
1066 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1067 if (I != ForwardRefs.end())
1068 return I->second;
1069
1070 // This is a new forward reference. Generate a unique name for it
1071 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1072
1073 // Yes, this is a hack. An Argument is the smallest instantiable value that
1074 // we can make as a placeholder for the real value. We'll replace these
1075 // Argument instances later.
1076 Out << "Argument* " << result << " = new Argument("
1077 << getCppName(V->getType()) << ");";
1078 nl(Out);
1079 ForwardRefs[V] = result;
1080 return result;
1081 }
1082
1083 // printInstruction - This member is called for each Instruction in a function.
1084 void CppWriter::printInstruction(const Instruction *I,
1085 const std::string& bbname) {
1086 std::string iName(getCppName(I));
1087
1088 // Before we emit this instruction, we need to take care of generating any
1089 // forward references. So, we get the names of all the operands in advance
Gabor Greif2f256f42010-05-04 09:23:54 +00001090 const unsigned Ops(I->getNumOperands());
1091 std::string* opNames = new std::string[Ops];
1092 for (unsigned i = 0; i < Ops; i++) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001093 opNames[i] = getOpName(I->getOperand(i));
1094 }
1095
1096 switch (I->getOpcode()) {
Dan Gohman26825a82008-06-09 14:09:13 +00001097 default:
1098 error("Invalid instruction");
1099 break;
1100
Anton Korobeynikov50276522008-04-23 22:29:24 +00001101 case Instruction::Ret: {
1102 const ReturnInst* ret = cast<ReturnInst>(I);
Nicolas Geoffray81d97c02010-02-23 19:42:44 +00001103 Out << "ReturnInst::Create(mod->getContext(), "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001104 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1105 break;
1106 }
1107 case Instruction::Br: {
1108 const BranchInst* br = cast<BranchInst>(I);
1109 Out << "BranchInst::Create(" ;
1110 if (br->getNumOperands() == 3 ) {
Anton Korobeynikovcffb5282009-05-04 19:10:38 +00001111 Out << opNames[2] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001112 << opNames[1] << ", "
Anton Korobeynikovcffb5282009-05-04 19:10:38 +00001113 << opNames[0] << ", ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001114
1115 } else if (br->getNumOperands() == 1) {
1116 Out << opNames[0] << ", ";
1117 } else {
1118 error("Branch with 2 operands?");
1119 }
1120 Out << bbname << ");";
1121 break;
1122 }
1123 case Instruction::Switch: {
Chris Lattner627b4702009-10-27 21:24:48 +00001124 const SwitchInst *SI = cast<SwitchInst>(I);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001125 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1126 << opNames[0] << ", "
1127 << opNames[1] << ", "
Chris Lattner627b4702009-10-27 21:24:48 +00001128 << SI->getNumCases() << ", " << bbname << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001129 nl(Out);
Chris Lattner627b4702009-10-27 21:24:48 +00001130 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001131 Out << iName << "->addCase("
1132 << opNames[i] << ", "
1133 << opNames[i+1] << ");";
1134 nl(Out);
1135 }
1136 break;
1137 }
Chris Lattnerab21db72009-10-28 00:19:10 +00001138 case Instruction::IndirectBr: {
1139 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1140 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
Chris Lattner627b4702009-10-27 21:24:48 +00001141 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1142 nl(Out);
1143 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1144 Out << iName << "->addDestination(" << opNames[i] << ");";
1145 nl(Out);
1146 }
1147 break;
1148 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001149 case Instruction::Invoke: {
1150 const InvokeInst* inv = cast<InvokeInst>(I);
1151 Out << "std::vector<Value*> " << iName << "_params;";
1152 nl(Out);
Gabor Greif2f256f42010-05-04 09:23:54 +00001153 for (unsigned i = 0; i < inv->getNumOperands() - 3; ++i) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001154 Out << iName << "_params.push_back("
1155 << opNames[i] << ");";
1156 nl(Out);
1157 }
1158 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
Gabor Greif2f256f42010-05-04 09:23:54 +00001159 << opNames[Ops - 3] << ", "
1160 << opNames[Ops - 2] << ", "
1161 << opNames[Ops - 1] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001162 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1163 printEscapedString(inv->getName());
1164 Out << "\", " << bbname << ");";
1165 nl(Out) << iName << "->setCallingConv(";
1166 printCallingConv(inv->getCallingConv());
1167 Out << ");";
Devang Patel05988662008-09-25 21:00:45 +00001168 printAttributes(inv->getAttributes(), iName);
1169 Out << iName << "->setAttributes(" << iName << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001170 nl(Out);
1171 break;
1172 }
1173 case Instruction::Unwind: {
1174 Out << "new UnwindInst("
1175 << bbname << ");";
1176 break;
1177 }
Reid Kleckner781c2b82009-08-19 22:38:37 +00001178 case Instruction::Unreachable: {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001179 Out << "new UnreachableInst("
Nicolas Geoffray81d97c02010-02-23 19:42:44 +00001180 << "mod->getContext(), "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001181 << bbname << ");";
1182 break;
1183 }
1184 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001185 case Instruction::FAdd:
Anton Korobeynikov50276522008-04-23 22:29:24 +00001186 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001187 case Instruction::FSub:
Anton Korobeynikov50276522008-04-23 22:29:24 +00001188 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001189 case Instruction::FMul:
Anton Korobeynikov50276522008-04-23 22:29:24 +00001190 case Instruction::UDiv:
1191 case Instruction::SDiv:
1192 case Instruction::FDiv:
1193 case Instruction::URem:
1194 case Instruction::SRem:
1195 case Instruction::FRem:
1196 case Instruction::And:
1197 case Instruction::Or:
1198 case Instruction::Xor:
1199 case Instruction::Shl:
1200 case Instruction::LShr:
1201 case Instruction::AShr:{
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001202 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001203 switch (I->getOpcode()) {
1204 case Instruction::Add: Out << "Instruction::Add"; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001205 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001206 case Instruction::Sub: Out << "Instruction::Sub"; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001207 case Instruction::FSub: Out << "Instruction::FSub"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001208 case Instruction::Mul: Out << "Instruction::Mul"; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001209 case Instruction::FMul: Out << "Instruction::FMul"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001210 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1211 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1212 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1213 case Instruction::URem:Out << "Instruction::URem"; break;
1214 case Instruction::SRem:Out << "Instruction::SRem"; break;
1215 case Instruction::FRem:Out << "Instruction::FRem"; break;
1216 case Instruction::And: Out << "Instruction::And"; break;
1217 case Instruction::Or: Out << "Instruction::Or"; break;
1218 case Instruction::Xor: Out << "Instruction::Xor"; break;
1219 case Instruction::Shl: Out << "Instruction::Shl"; break;
1220 case Instruction::LShr:Out << "Instruction::LShr"; break;
1221 case Instruction::AShr:Out << "Instruction::AShr"; break;
1222 default: Out << "Instruction::BadOpCode"; break;
1223 }
1224 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1225 printEscapedString(I->getName());
1226 Out << "\", " << bbname << ");";
1227 break;
1228 }
1229 case Instruction::FCmp: {
Anton Korobeynikovd083dfb2009-08-21 12:50:54 +00001230 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001231 switch (cast<FCmpInst>(I)->getPredicate()) {
1232 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1233 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1234 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1235 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1236 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1237 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1238 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1239 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1240 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1241 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1242 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1243 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1244 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1245 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1246 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1247 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1248 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1249 }
1250 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1251 printEscapedString(I->getName());
Anton Korobeynikovd083dfb2009-08-21 12:50:54 +00001252 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001253 break;
1254 }
1255 case Instruction::ICmp: {
Reid Kleckner781c2b82009-08-19 22:38:37 +00001256 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001257 switch (cast<ICmpInst>(I)->getPredicate()) {
1258 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1259 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1260 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1261 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1262 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1263 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1264 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1265 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1266 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1267 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1268 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1269 }
1270 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1271 printEscapedString(I->getName());
Reid Kleckner781c2b82009-08-19 22:38:37 +00001272 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001273 break;
1274 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001275 case Instruction::Alloca: {
1276 const AllocaInst* allocaI = cast<AllocaInst>(I);
1277 Out << "AllocaInst* " << iName << " = new AllocaInst("
1278 << getCppName(allocaI->getAllocatedType()) << ", ";
1279 if (allocaI->isArrayAllocation())
1280 Out << opNames[0] << ", ";
1281 Out << "\"";
1282 printEscapedString(allocaI->getName());
1283 Out << "\", " << bbname << ");";
1284 if (allocaI->getAlignment())
1285 nl(Out) << iName << "->setAlignment("
1286 << allocaI->getAlignment() << ");";
1287 break;
1288 }
1289 case Instruction::Load:{
1290 const LoadInst* load = cast<LoadInst>(I);
1291 Out << "LoadInst* " << iName << " = new LoadInst("
1292 << opNames[0] << ", \"";
1293 printEscapedString(load->getName());
1294 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1295 << ", " << bbname << ");";
1296 break;
1297 }
1298 case Instruction::Store: {
1299 const StoreInst* store = cast<StoreInst>(I);
Anton Korobeynikovb0714db2008-11-09 02:54:13 +00001300 Out << " new StoreInst("
Anton Korobeynikov50276522008-04-23 22:29:24 +00001301 << opNames[0] << ", "
1302 << opNames[1] << ", "
1303 << (store->isVolatile() ? "true" : "false")
1304 << ", " << bbname << ");";
1305 break;
1306 }
1307 case Instruction::GetElementPtr: {
1308 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1309 if (gep->getNumOperands() <= 2) {
1310 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1311 << opNames[0];
1312 if (gep->getNumOperands() == 2)
1313 Out << ", " << opNames[1];
1314 } else {
1315 Out << "std::vector<Value*> " << iName << "_indices;";
1316 nl(Out);
1317 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1318 Out << iName << "_indices.push_back("
1319 << opNames[i] << ");";
1320 nl(Out);
1321 }
1322 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1323 << opNames[0] << ", " << iName << "_indices.begin(), "
1324 << iName << "_indices.end()";
1325 }
1326 Out << ", \"";
1327 printEscapedString(gep->getName());
1328 Out << "\", " << bbname << ");";
1329 break;
1330 }
1331 case Instruction::PHI: {
1332 const PHINode* phi = cast<PHINode>(I);
1333
1334 Out << "PHINode* " << iName << " = PHINode::Create("
1335 << getCppName(phi->getType()) << ", \"";
1336 printEscapedString(phi->getName());
1337 Out << "\", " << bbname << ");";
1338 nl(Out) << iName << "->reserveOperandSpace("
1339 << phi->getNumIncomingValues()
1340 << ");";
1341 nl(Out);
1342 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1343 Out << iName << "->addIncoming("
1344 << opNames[i] << ", " << opNames[i+1] << ");";
1345 nl(Out);
1346 }
1347 break;
1348 }
1349 case Instruction::Trunc:
1350 case Instruction::ZExt:
1351 case Instruction::SExt:
1352 case Instruction::FPTrunc:
1353 case Instruction::FPExt:
1354 case Instruction::FPToUI:
1355 case Instruction::FPToSI:
1356 case Instruction::UIToFP:
1357 case Instruction::SIToFP:
1358 case Instruction::PtrToInt:
1359 case Instruction::IntToPtr:
1360 case Instruction::BitCast: {
1361 const CastInst* cst = cast<CastInst>(I);
1362 Out << "CastInst* " << iName << " = new ";
1363 switch (I->getOpcode()) {
1364 case Instruction::Trunc: Out << "TruncInst"; break;
1365 case Instruction::ZExt: Out << "ZExtInst"; break;
1366 case Instruction::SExt: Out << "SExtInst"; break;
1367 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1368 case Instruction::FPExt: Out << "FPExtInst"; break;
1369 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1370 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1371 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1372 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1373 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1374 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1375 case Instruction::BitCast: Out << "BitCastInst"; break;
1376 default: assert(!"Unreachable"); break;
1377 }
1378 Out << "(" << opNames[0] << ", "
1379 << getCppName(cst->getType()) << ", \"";
1380 printEscapedString(cst->getName());
1381 Out << "\", " << bbname << ");";
1382 break;
1383 }
1384 case Instruction::Call:{
1385 const CallInst* call = cast<CallInst>(I);
Gabor Greif0c8f7dc2009-03-25 06:32:59 +00001386 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001387 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1388 << getCppName(ila->getFunctionType()) << ", \""
1389 << ila->getAsmString() << "\", \""
1390 << ila->getConstraintString() << "\","
1391 << (ila->hasSideEffects() ? "true" : "false") << ");";
1392 nl(Out);
1393 }
1394 if (call->getNumOperands() > 2) {
1395 Out << "std::vector<Value*> " << iName << "_params;";
1396 nl(Out);
Eric Christopher551754c2010-04-16 23:37:20 +00001397 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001398 Out << iName << "_params.push_back(" << opNames[i] << ");";
1399 nl(Out);
1400 }
1401 Out << "CallInst* " << iName << " = CallInst::Create("
Eric Christopher551754c2010-04-16 23:37:20 +00001402 << opNames[0] << ", " << iName << "_params.begin(), "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001403 << iName << "_params.end(), \"";
1404 } else if (call->getNumOperands() == 2) {
1405 Out << "CallInst* " << iName << " = CallInst::Create("
Eric Christopher551754c2010-04-16 23:37:20 +00001406 << opNames[0] << ", " << opNames[1] << ", \"";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001407 } else {
Eric Christopher551754c2010-04-16 23:37:20 +00001408 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
Anton Korobeynikov50276522008-04-23 22:29:24 +00001409 << ", \"";
1410 }
1411 printEscapedString(call->getName());
1412 Out << "\", " << bbname << ");";
1413 nl(Out) << iName << "->setCallingConv(";
1414 printCallingConv(call->getCallingConv());
1415 Out << ");";
1416 nl(Out) << iName << "->setTailCall("
1417 << (call->isTailCall() ? "true":"false");
1418 Out << ");";
Devang Patel05988662008-09-25 21:00:45 +00001419 printAttributes(call->getAttributes(), iName);
1420 Out << iName << "->setAttributes(" << iName << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001421 nl(Out);
1422 break;
1423 }
1424 case Instruction::Select: {
1425 const SelectInst* sel = cast<SelectInst>(I);
1426 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1427 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1428 printEscapedString(sel->getName());
1429 Out << "\", " << bbname << ");";
1430 break;
1431 }
1432 case Instruction::UserOp1:
1433 /// FALL THROUGH
1434 case Instruction::UserOp2: {
1435 /// FIXME: What should be done here?
1436 break;
1437 }
1438 case Instruction::VAArg: {
1439 const VAArgInst* va = cast<VAArgInst>(I);
1440 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1441 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1442 printEscapedString(va->getName());
1443 Out << "\", " << bbname << ");";
1444 break;
1445 }
1446 case Instruction::ExtractElement: {
1447 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1448 Out << "ExtractElementInst* " << getCppName(eei)
1449 << " = new ExtractElementInst(" << opNames[0]
1450 << ", " << opNames[1] << ", \"";
1451 printEscapedString(eei->getName());
1452 Out << "\", " << bbname << ");";
1453 break;
1454 }
1455 case Instruction::InsertElement: {
1456 const InsertElementInst* iei = cast<InsertElementInst>(I);
1457 Out << "InsertElementInst* " << getCppName(iei)
1458 << " = InsertElementInst::Create(" << opNames[0]
1459 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1460 printEscapedString(iei->getName());
1461 Out << "\", " << bbname << ");";
1462 break;
1463 }
1464 case Instruction::ShuffleVector: {
1465 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1466 Out << "ShuffleVectorInst* " << getCppName(svi)
1467 << " = new ShuffleVectorInst(" << opNames[0]
1468 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1469 printEscapedString(svi->getName());
1470 Out << "\", " << bbname << ");";
1471 break;
1472 }
Dan Gohman75146a62008-06-09 14:12:10 +00001473 case Instruction::ExtractValue: {
1474 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1475 Out << "std::vector<unsigned> " << iName << "_indices;";
1476 nl(Out);
1477 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1478 Out << iName << "_indices.push_back("
1479 << evi->idx_begin()[i] << ");";
1480 nl(Out);
1481 }
1482 Out << "ExtractValueInst* " << getCppName(evi)
1483 << " = ExtractValueInst::Create(" << opNames[0]
1484 << ", "
1485 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1486 printEscapedString(evi->getName());
1487 Out << "\", " << bbname << ");";
1488 break;
1489 }
1490 case Instruction::InsertValue: {
1491 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1492 Out << "std::vector<unsigned> " << iName << "_indices;";
1493 nl(Out);
1494 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1495 Out << iName << "_indices.push_back("
1496 << ivi->idx_begin()[i] << ");";
1497 nl(Out);
1498 }
1499 Out << "InsertValueInst* " << getCppName(ivi)
1500 << " = InsertValueInst::Create(" << opNames[0]
1501 << ", " << opNames[1] << ", "
1502 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1503 printEscapedString(ivi->getName());
1504 Out << "\", " << bbname << ");";
1505 break;
1506 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001507 }
1508 DefinedValues.insert(I);
1509 nl(Out);
1510 delete [] opNames;
1511}
1512
1513 // Print out the types, constants and declarations needed by one function
1514 void CppWriter::printFunctionUses(const Function* F) {
1515 nl(Out) << "// Type Definitions"; nl(Out);
1516 if (!is_inline) {
1517 // Print the function's return type
1518 printType(F->getReturnType());
1519
1520 // Print the function's function type
1521 printType(F->getFunctionType());
1522
1523 // Print the types of each of the function's arguments
1524 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1525 AI != AE; ++AI) {
1526 printType(AI->getType());
1527 }
1528 }
1529
1530 // Print type definitions for every type referenced by an instruction and
1531 // make a note of any global values or constants that are referenced
1532 SmallPtrSet<GlobalValue*,64> gvs;
1533 SmallPtrSet<Constant*,64> consts;
1534 for (Function::const_iterator BB = F->begin(), BE = F->end();
1535 BB != BE; ++BB){
1536 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1537 I != E; ++I) {
1538 // Print the type of the instruction itself
1539 printType(I->getType());
1540
1541 // Print the type of each of the instruction's operands
1542 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1543 Value* operand = I->getOperand(i);
1544 printType(operand->getType());
1545
1546 // If the operand references a GVal or Constant, make a note of it
1547 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1548 gvs.insert(GV);
1549 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1550 if (GVar->hasInitializer())
1551 consts.insert(GVar->getInitializer());
1552 } else if (Constant* C = dyn_cast<Constant>(operand))
1553 consts.insert(C);
1554 }
1555 }
1556 }
1557
1558 // Print the function declarations for any functions encountered
1559 nl(Out) << "// Function Declarations"; nl(Out);
1560 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1561 I != E; ++I) {
1562 if (Function* Fun = dyn_cast<Function>(*I)) {
1563 if (!is_inline || Fun != F)
1564 printFunctionHead(Fun);
1565 }
1566 }
1567
1568 // Print the global variable declarations for any variables encountered
1569 nl(Out) << "// Global Variable Declarations"; nl(Out);
1570 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1571 I != E; ++I) {
1572 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1573 printVariableHead(F);
1574 }
1575
1576 // Print the constants found
1577 nl(Out) << "// Constant Definitions"; nl(Out);
1578 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1579 E = consts.end(); I != E; ++I) {
1580 printConstant(*I);
1581 }
1582
1583 // Process the global variables definitions now that all the constants have
1584 // been emitted. These definitions just couple the gvars with their constant
1585 // initializers.
1586 nl(Out) << "// Global Variable Definitions"; nl(Out);
1587 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1588 I != E; ++I) {
1589 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1590 printVariableBody(GV);
1591 }
1592 }
1593
1594 void CppWriter::printFunctionHead(const Function* F) {
1595 nl(Out) << "Function* " << getCppName(F);
1596 if (is_inline) {
1597 Out << " = mod->getFunction(\"";
1598 printEscapedString(F->getName());
1599 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1600 nl(Out) << "if (!" << getCppName(F) << ") {";
1601 nl(Out) << getCppName(F);
1602 }
1603 Out<< " = Function::Create(";
1604 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1605 nl(Out) << "/*Linkage=*/";
1606 printLinkageType(F->getLinkage());
1607 Out << ",";
1608 nl(Out) << "/*Name=*/\"";
1609 printEscapedString(F->getName());
1610 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1611 nl(Out,-1);
1612 printCppName(F);
1613 Out << "->setCallingConv(";
1614 printCallingConv(F->getCallingConv());
1615 Out << ");";
1616 nl(Out);
1617 if (F->hasSection()) {
1618 printCppName(F);
1619 Out << "->setSection(\"" << F->getSection() << "\");";
1620 nl(Out);
1621 }
1622 if (F->getAlignment()) {
1623 printCppName(F);
1624 Out << "->setAlignment(" << F->getAlignment() << ");";
1625 nl(Out);
1626 }
1627 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1628 printCppName(F);
1629 Out << "->setVisibility(";
1630 printVisibilityType(F->getVisibility());
1631 Out << ");";
1632 nl(Out);
1633 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001634 if (F->hasGC()) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001635 printCppName(F);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001636 Out << "->setGC(\"" << F->getGC() << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001637 nl(Out);
1638 }
1639 if (is_inline) {
1640 Out << "}";
1641 nl(Out);
1642 }
Devang Patel05988662008-09-25 21:00:45 +00001643 printAttributes(F->getAttributes(), getCppName(F));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001644 printCppName(F);
Devang Patel05988662008-09-25 21:00:45 +00001645 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001646 nl(Out);
1647 }
1648
1649 void CppWriter::printFunctionBody(const Function *F) {
1650 if (F->isDeclaration())
1651 return; // external functions have no bodies.
1652
1653 // Clear the DefinedValues and ForwardRefs maps because we can't have
1654 // cross-function forward refs
1655 ForwardRefs.clear();
1656 DefinedValues.clear();
1657
1658 // Create all the argument values
1659 if (!is_inline) {
1660 if (!F->arg_empty()) {
1661 Out << "Function::arg_iterator args = " << getCppName(F)
1662 << "->arg_begin();";
1663 nl(Out);
1664 }
1665 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1666 AI != AE; ++AI) {
1667 Out << "Value* " << getCppName(AI) << " = args++;";
1668 nl(Out);
1669 if (AI->hasName()) {
1670 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1671 nl(Out);
1672 }
1673 }
1674 }
1675
1676 // Create all the basic blocks
1677 nl(Out);
1678 for (Function::const_iterator BI = F->begin(), BE = F->end();
1679 BI != BE; ++BI) {
1680 std::string bbname(getCppName(BI));
Owen Anderson267a0ff2009-08-14 17:41:33 +00001681 Out << "BasicBlock* " << bbname <<
Nicolas Geoffray81d97c02010-02-23 19:42:44 +00001682 " = BasicBlock::Create(mod->getContext(), \"";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001683 if (BI->hasName())
1684 printEscapedString(BI->getName());
1685 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1686 nl(Out);
1687 }
1688
1689 // Output all of its basic blocks... for the function
1690 for (Function::const_iterator BI = F->begin(), BE = F->end();
1691 BI != BE; ++BI) {
1692 std::string bbname(getCppName(BI));
1693 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1694 nl(Out);
1695
1696 // Output all of the instructions in the basic block...
1697 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1698 I != E; ++I) {
1699 printInstruction(I,bbname);
1700 }
1701 }
1702
1703 // Loop over the ForwardRefs and resolve them now that all instructions
1704 // are generated.
1705 if (!ForwardRefs.empty()) {
1706 nl(Out) << "// Resolve Forward References";
1707 nl(Out);
1708 }
1709
1710 while (!ForwardRefs.empty()) {
1711 ForwardRefMap::iterator I = ForwardRefs.begin();
1712 Out << I->second << "->replaceAllUsesWith("
1713 << getCppName(I->first) << "); delete " << I->second << ";";
1714 nl(Out);
1715 ForwardRefs.erase(I);
1716 }
1717 }
1718
1719 void CppWriter::printInline(const std::string& fname,
1720 const std::string& func) {
1721 const Function* F = TheModule->getFunction(func);
1722 if (!F) {
1723 error(std::string("Function '") + func + "' not found in input module");
1724 return;
1725 }
1726 if (F->isDeclaration()) {
1727 error(std::string("Function '") + func + "' is external!");
1728 return;
1729 }
1730 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1731 << getCppName(F);
1732 unsigned arg_count = 1;
1733 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1734 AI != AE; ++AI) {
1735 Out << ", Value* arg_" << arg_count;
1736 }
1737 Out << ") {";
1738 nl(Out);
1739 is_inline = true;
1740 printFunctionUses(F);
1741 printFunctionBody(F);
1742 is_inline = false;
1743 Out << "return " << getCppName(F->begin()) << ";";
1744 nl(Out) << "}";
1745 nl(Out);
1746 }
1747
1748 void CppWriter::printModuleBody() {
1749 // Print out all the type definitions
1750 nl(Out) << "// Type Definitions"; nl(Out);
1751 printTypes(TheModule);
1752
1753 // Functions can call each other and global variables can reference them so
1754 // define all the functions first before emitting their function bodies.
1755 nl(Out) << "// Function Declarations"; nl(Out);
1756 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1757 I != E; ++I)
1758 printFunctionHead(I);
1759
1760 // Process the global variables declarations. We can't initialze them until
1761 // after the constants are printed so just print a header for each global
1762 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1763 for (Module::const_global_iterator I = TheModule->global_begin(),
1764 E = TheModule->global_end(); I != E; ++I) {
1765 printVariableHead(I);
1766 }
1767
1768 // Print out all the constants definitions. Constants don't recurse except
1769 // through GlobalValues. All GlobalValues have been declared at this point
1770 // so we can proceed to generate the constants.
1771 nl(Out) << "// Constant Definitions"; nl(Out);
1772 printConstants(TheModule);
1773
1774 // Process the global variables definitions now that all the constants have
1775 // been emitted. These definitions just couple the gvars with their constant
1776 // initializers.
1777 nl(Out) << "// Global Variable Definitions"; nl(Out);
1778 for (Module::const_global_iterator I = TheModule->global_begin(),
1779 E = TheModule->global_end(); I != E; ++I) {
1780 printVariableBody(I);
1781 }
1782
1783 // Finally, we can safely put out all of the function bodies.
1784 nl(Out) << "// Function Definitions"; nl(Out);
1785 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1786 I != E; ++I) {
1787 if (!I->isDeclaration()) {
1788 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1789 << ")";
1790 nl(Out) << "{";
1791 nl(Out,1);
1792 printFunctionBody(I);
1793 nl(Out,-1) << "}";
1794 nl(Out);
1795 }
1796 }
1797 }
1798
1799 void CppWriter::printProgram(const std::string& fname,
1800 const std::string& mName) {
Owen Anderson267a0ff2009-08-14 17:41:33 +00001801 Out << "#include <llvm/LLVMContext.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001802 Out << "#include <llvm/Module.h>\n";
1803 Out << "#include <llvm/DerivedTypes.h>\n";
1804 Out << "#include <llvm/Constants.h>\n";
1805 Out << "#include <llvm/GlobalVariable.h>\n";
1806 Out << "#include <llvm/Function.h>\n";
1807 Out << "#include <llvm/CallingConv.h>\n";
1808 Out << "#include <llvm/BasicBlock.h>\n";
1809 Out << "#include <llvm/Instructions.h>\n";
1810 Out << "#include <llvm/InlineAsm.h>\n";
David Greene71847812009-07-14 20:18:05 +00001811 Out << "#include <llvm/Support/FormattedStream.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001812 Out << "#include <llvm/Support/MathExtras.h>\n";
1813 Out << "#include <llvm/Pass.h>\n";
1814 Out << "#include <llvm/PassManager.h>\n";
Nicolas Geoffray9474ede2008-05-14 07:52:03 +00001815 Out << "#include <llvm/ADT/SmallVector.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001816 Out << "#include <llvm/Analysis/Verifier.h>\n";
1817 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1818 Out << "#include <algorithm>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001819 Out << "using namespace llvm;\n\n";
1820 Out << "Module* " << fname << "();\n\n";
1821 Out << "int main(int argc, char**argv) {\n";
1822 Out << " Module* Mod = " << fname << "();\n";
1823 Out << " verifyModule(*Mod, PrintMessageAction);\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001824 Out << " PassManager PM;\n";
Dan Gohmanf9231292008-12-08 07:07:24 +00001825 Out << " PM.add(createPrintModulePass(&outs()));\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001826 Out << " PM.run(*Mod);\n";
1827 Out << " return 0;\n";
1828 Out << "}\n\n";
1829 printModule(fname,mName);
1830 }
1831
1832 void CppWriter::printModule(const std::string& fname,
1833 const std::string& mName) {
1834 nl(Out) << "Module* " << fname << "() {";
1835 nl(Out,1) << "// Module Construction";
Nick Lewyckyb8b73472009-06-26 04:33:37 +00001836 nl(Out) << "Module* mod = new Module(\"";
1837 printEscapedString(mName);
Owen Anderson267a0ff2009-08-14 17:41:33 +00001838 Out << "\", getGlobalContext());";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001839 if (!TheModule->getTargetTriple().empty()) {
1840 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1841 }
1842 if (!TheModule->getTargetTriple().empty()) {
1843 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1844 << "\");";
1845 }
1846
1847 if (!TheModule->getModuleInlineAsm().empty()) {
1848 nl(Out) << "mod->setModuleInlineAsm(\"";
1849 printEscapedString(TheModule->getModuleInlineAsm());
1850 Out << "\");";
1851 }
1852 nl(Out);
1853
1854 // Loop over the dependent libraries and emit them.
1855 Module::lib_iterator LI = TheModule->lib_begin();
1856 Module::lib_iterator LE = TheModule->lib_end();
1857 while (LI != LE) {
1858 Out << "mod->addLibrary(\"" << *LI << "\");";
1859 nl(Out);
1860 ++LI;
1861 }
1862 printModuleBody();
1863 nl(Out) << "return mod;";
1864 nl(Out,-1) << "}";
1865 nl(Out);
1866 }
1867
1868 void CppWriter::printContents(const std::string& fname,
1869 const std::string& mName) {
1870 Out << "\nModule* " << fname << "(Module *mod) {\n";
Nick Lewyckyb8b73472009-06-26 04:33:37 +00001871 Out << "\nmod->setModuleIdentifier(\"";
1872 printEscapedString(mName);
1873 Out << "\");\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001874 printModuleBody();
1875 Out << "\nreturn mod;\n";
1876 Out << "\n}\n";
1877 }
1878
1879 void CppWriter::printFunction(const std::string& fname,
1880 const std::string& funcName) {
1881 const Function* F = TheModule->getFunction(funcName);
1882 if (!F) {
1883 error(std::string("Function '") + funcName + "' not found in input module");
1884 return;
1885 }
1886 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1887 printFunctionUses(F);
1888 printFunctionHead(F);
1889 printFunctionBody(F);
1890 Out << "return " << getCppName(F) << ";\n";
1891 Out << "}\n";
1892 }
1893
1894 void CppWriter::printFunctions() {
1895 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1896 Module::const_iterator I = funcs.begin();
1897 Module::const_iterator IE = funcs.end();
1898
1899 for (; I != IE; ++I) {
1900 const Function &func = *I;
1901 if (!func.isDeclaration()) {
1902 std::string name("define_");
1903 name += func.getName();
1904 printFunction(name, func.getName());
1905 }
1906 }
1907 }
1908
1909 void CppWriter::printVariable(const std::string& fname,
1910 const std::string& varName) {
1911 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1912
1913 if (!GV) {
1914 error(std::string("Variable '") + varName + "' not found in input module");
1915 return;
1916 }
1917 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1918 printVariableUses(GV);
1919 printVariableHead(GV);
1920 printVariableBody(GV);
1921 Out << "return " << getCppName(GV) << ";\n";
1922 Out << "}\n";
1923 }
1924
1925 void CppWriter::printType(const std::string& fname,
1926 const std::string& typeName) {
1927 const Type* Ty = TheModule->getTypeByName(typeName);
1928 if (!Ty) {
1929 error(std::string("Type '") + typeName + "' not found in input module");
1930 return;
1931 }
1932 Out << "\nType* " << fname << "(Module *mod) {\n";
1933 printType(Ty);
1934 Out << "return " << getCppName(Ty) << ";\n";
1935 Out << "}\n";
1936 }
1937
1938 bool CppWriter::runOnModule(Module &M) {
1939 TheModule = &M;
1940
1941 // Emit a header
1942 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1943
1944 // Get the name of the function we're supposed to generate
1945 std::string fname = FuncName.getValue();
1946
1947 // Get the name of the thing we are to generate
1948 std::string tgtname = NameToGenerate.getValue();
1949 if (GenerationType == GenModule ||
1950 GenerationType == GenContents ||
1951 GenerationType == GenProgram ||
1952 GenerationType == GenFunctions) {
1953 if (tgtname == "!bad!") {
1954 if (M.getModuleIdentifier() == "-")
1955 tgtname = "<stdin>";
1956 else
1957 tgtname = M.getModuleIdentifier();
1958 }
1959 } else if (tgtname == "!bad!")
1960 error("You must use the -for option with -gen-{function,variable,type}");
1961
1962 switch (WhatToGenerate(GenerationType)) {
1963 case GenProgram:
1964 if (fname.empty())
1965 fname = "makeLLVMModule";
1966 printProgram(fname,tgtname);
1967 break;
1968 case GenModule:
1969 if (fname.empty())
1970 fname = "makeLLVMModule";
1971 printModule(fname,tgtname);
1972 break;
1973 case GenContents:
1974 if (fname.empty())
1975 fname = "makeLLVMModuleContents";
1976 printContents(fname,tgtname);
1977 break;
1978 case GenFunction:
1979 if (fname.empty())
1980 fname = "makeLLVMFunction";
1981 printFunction(fname,tgtname);
1982 break;
1983 case GenFunctions:
1984 printFunctions();
1985 break;
1986 case GenInline:
1987 if (fname.empty())
1988 fname = "makeLLVMInline";
1989 printInline(fname,tgtname);
1990 break;
1991 case GenVariable:
1992 if (fname.empty())
1993 fname = "makeLLVMVariable";
1994 printVariable(fname,tgtname);
1995 break;
1996 case GenType:
1997 if (fname.empty())
1998 fname = "makeLLVMType";
1999 printType(fname,tgtname);
2000 break;
2001 default:
2002 error("Invalid generation option");
2003 }
2004
2005 return false;
2006 }
2007}
2008
2009char CppWriter::ID = 0;
2010
2011//===----------------------------------------------------------------------===//
2012// External Interface declaration
2013//===----------------------------------------------------------------------===//
2014
Dan Gohman99dca4f2010-05-11 19:57:55 +00002015bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2016 formatted_raw_ostream &o,
2017 CodeGenFileType FileType,
2018 CodeGenOpt::Level OptLevel,
2019 bool DisableVerify) {
Chris Lattner211edae2010-02-02 21:06:45 +00002020 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002021 PM.add(new CppWriter(o));
2022 return false;
2023}