blob: 38134d9189b70080c82da92d066af2f0e48f1844 [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"
26#include "llvm/Target/TargetMachineRegistry.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/Support/CommandLine.h"
Bill Wendling1a53ead2008-07-27 23:18:30 +000031#include "llvm/Support/Streams.h"
Owen Andersoncb371882008-08-21 00:14:44 +000032#include "llvm/Support/raw_ostream.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000033#include "llvm/Config/config.h"
34#include <algorithm>
Anton Korobeynikov50276522008-04-23 22:29:24 +000035#include <set>
36
37using namespace llvm;
38
39static cl::opt<std::string>
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000040FuncName("cppfname", cl::desc("Specify the name of the generated function"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000041 cl::value_desc("function name"));
42
43enum WhatToGenerate {
44 GenProgram,
45 GenModule,
46 GenContents,
47 GenFunction,
48 GenFunctions,
49 GenInline,
50 GenVariable,
51 GenType
52};
53
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000054static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000055 cl::desc("Choose what kind of output to generate"),
56 cl::init(GenProgram),
57 cl::values(
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000058 clEnumValN(GenProgram, "program", "Generate a complete program"),
59 clEnumValN(GenModule, "module", "Generate a module definition"),
60 clEnumValN(GenContents, "contents", "Generate contents of a module"),
61 clEnumValN(GenFunction, "function", "Generate a function definition"),
62 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
63 clEnumValN(GenInline, "inline", "Generate an inline function"),
64 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
65 clEnumValN(GenType, "type", "Generate a type definition"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000066 clEnumValEnd
67 )
68);
69
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000070static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000071 cl::desc("Specify the name of the thing to generate"),
72 cl::init("!bad!"));
73
Oscar Fuentes92adc192008-11-15 21:36:30 +000074/// CppBackendTargetMachineModule - Note that this is used on hosts
75/// that cannot link in a library unless there are references into the
76/// library. In particular, it seems that it is not possible to get
77/// things to work on Win32 without this. Though it is unused, do not
78/// remove it.
79extern "C" int CppBackendTargetMachineModule;
80int CppBackendTargetMachineModule = 0;
81
Dan Gohman844731a2008-05-13 00:00:25 +000082// Register the target.
Dan Gohmanb8cab922008-10-14 20:25:08 +000083static RegisterTarget<CPPTargetMachine> X("cpp", "C++ backend");
Anton Korobeynikov50276522008-04-23 22:29:24 +000084
Dan Gohman844731a2008-05-13 00:00:25 +000085namespace {
Anton Korobeynikov50276522008-04-23 22:29:24 +000086 typedef std::vector<const Type*> TypeList;
87 typedef std::map<const Type*,std::string> TypeMap;
88 typedef std::map<const Value*,std::string> ValueMap;
89 typedef std::set<std::string> NameSet;
90 typedef std::set<const Type*> TypeSet;
91 typedef std::set<const Value*> ValueSet;
92 typedef std::map<const Value*,std::string> ForwardRefMap;
93
94 /// CppWriter - This class is the main chunk of code that converts an LLVM
95 /// module to a C++ translation unit.
96 class CppWriter : public ModulePass {
97 const char* progname;
Owen Andersoncb371882008-08-21 00:14:44 +000098 raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +000099 const Module *TheModule;
100 uint64_t uniqueNum;
101 TypeMap TypeNames;
102 ValueMap ValueNames;
103 TypeMap UnresolvedTypes;
104 TypeList TypeStack;
105 NameSet UsedNames;
106 TypeSet DefinedTypes;
107 ValueSet DefinedValues;
108 ForwardRefMap ForwardRefs;
109 bool is_inline;
110
111 public:
112 static char ID;
Owen Andersoncb371882008-08-21 00:14:44 +0000113 explicit CppWriter(raw_ostream &o) :
Dan Gohmanae73dc12008-09-04 17:05:41 +0000114 ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000115
116 virtual const char *getPassName() const { return "C++ backend"; }
117
118 bool runOnModule(Module &M);
119
Anton Korobeynikov50276522008-04-23 22:29:24 +0000120 void printProgram(const std::string& fname, const std::string& modName );
121 void printModule(const std::string& fname, const std::string& modName );
122 void printContents(const std::string& fname, const std::string& modName );
123 void printFunction(const std::string& fname, const std::string& funcName );
124 void printFunctions();
125 void printInline(const std::string& fname, const std::string& funcName );
126 void printVariable(const std::string& fname, const std::string& varName );
127 void printType(const std::string& fname, const std::string& typeName );
128
129 void error(const std::string& msg);
130
131 private:
132 void printLinkageType(GlobalValue::LinkageTypes LT);
133 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
134 void printCallingConv(unsigned cc);
135 void printEscapedString(const std::string& str);
136 void printCFP(const ConstantFP* CFP);
137
138 std::string getCppName(const Type* val);
139 inline void printCppName(const Type* val);
140
141 std::string getCppName(const Value* val);
142 inline void printCppName(const Value* val);
143
Devang Patel05988662008-09-25 21:00:45 +0000144 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000145 bool printTypeInternal(const Type* Ty);
146 inline void printType(const Type* Ty);
147 void printTypes(const Module* M);
148
149 void printConstant(const Constant *CPV);
150 void printConstants(const Module* M);
151
152 void printVariableUses(const GlobalVariable *GV);
153 void printVariableHead(const GlobalVariable *GV);
154 void printVariableBody(const GlobalVariable *GV);
155
156 void printFunctionUses(const Function *F);
157 void printFunctionHead(const Function *F);
158 void printFunctionBody(const Function *F);
159 void printInstruction(const Instruction *I, const std::string& bbname);
160 std::string getOpName(Value*);
161
162 void printModuleBody();
163 };
164
165 static unsigned indent_level = 0;
Owen Andersoncb371882008-08-21 00:14:44 +0000166 inline raw_ostream& nl(raw_ostream& Out, int delta = 0) {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000167 Out << "\n";
168 if (delta >= 0 || indent_level >= unsigned(-delta))
169 indent_level += delta;
170 for (unsigned i = 0; i < indent_level; ++i)
171 Out << " ";
172 return Out;
173 }
174
175 inline void in() { indent_level++; }
176 inline void out() { if (indent_level >0) indent_level--; }
177
178 inline void
179 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
185 inline std::string
186 getTypePrefix(const Type* Ty ) {
187 switch (Ty->getTypeID()) {
188 case Type::VoidTyID: return "void_";
189 case Type::IntegerTyID:
190 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
191 "_";
192 case Type::FloatTyID: return "float_";
193 case Type::DoubleTyID: return "double_";
194 case Type::LabelTyID: return "label_";
195 case Type::FunctionTyID: return "func_";
196 case Type::StructTyID: return "struct_";
197 case Type::ArrayTyID: return "array_";
198 case Type::PointerTyID: return "ptr_";
199 case Type::VectorTyID: return "packed_";
200 case Type::OpaqueTyID: return "opaque_";
201 default: return "other_";
202 }
203 return "unknown_";
204 }
205
206 // Looks up the type in the symbol table and returns a pointer to its name or
207 // a null pointer if it wasn't found. Note that this isn't the same as the
208 // Mode::getTypeName function which will return an empty string, not a null
209 // pointer if the name is not found.
210 inline const std::string*
211 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
212 TypeSymbolTable::const_iterator TI = ST.begin();
213 TypeSymbolTable::const_iterator TE = ST.end();
214 for (;TI != TE; ++TI)
215 if (TI->second == Ty)
216 return &(TI->first);
217 return 0;
218 }
219
220 void CppWriter::error(const std::string& msg) {
Bill Wendling1a53ead2008-07-27 23:18:30 +0000221 cerr << progname << ": " << msg << "\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000222 exit(2);
223 }
224
225 // printCFP - Print a floating point constant .. very carefully :)
226 // This makes sure that conversion to/from floating yields the same binary
227 // result so that we don't lose precision.
228 void CppWriter::printCFP(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000229 bool ignored;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000230 APFloat APF = APFloat(CFP->getValueAPF()); // copy
231 if (CFP->getType() == Type::FloatTy)
Dale Johannesen23a98552008-10-09 23:00:39 +0000232 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000233 Out << "ConstantFP::get(";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000234 Out << "APFloat(";
235#if HAVE_PRINTF_A
236 char Buffer[100];
237 sprintf(Buffer, "%A", APF.convertToDouble());
238 if ((!strncmp(Buffer, "0x", 2) ||
239 !strncmp(Buffer, "-0x", 3) ||
240 !strncmp(Buffer, "+0x", 3)) &&
241 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
242 if (CFP->getType() == Type::DoubleTy)
243 Out << "BitsToDouble(" << Buffer << ")";
244 else
245 Out << "BitsToFloat((float)" << Buffer << ")";
246 Out << ")";
247 } else {
248#endif
249 std::string StrVal = ftostr(CFP->getValueAPF());
250
251 while (StrVal[0] == ' ')
252 StrVal.erase(StrVal.begin());
253
254 // Check to make sure that the stringized number is not some string like
255 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
256 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
257 ((StrVal[0] == '-' || StrVal[0] == '+') &&
258 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
259 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
260 if (CFP->getType() == Type::DoubleTy)
261 Out << StrVal;
262 else
263 Out << StrVal << "f";
264 } else if (CFP->getType() == Type::DoubleTy)
Owen Andersoncb371882008-08-21 00:14:44 +0000265 Out << "BitsToDouble(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000266 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000267 << "ULL) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000268 else
Owen Andersoncb371882008-08-21 00:14:44 +0000269 Out << "BitsToFloat(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000270 << utohexstr((uint32_t)CFP->getValueAPF().
271 bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000272 << "U) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000273 Out << ")";
274#if HAVE_PRINTF_A
275 }
276#endif
277 Out << ")";
278 }
279
280 void CppWriter::printCallingConv(unsigned cc){
281 // Print the calling convention.
282 switch (cc) {
283 case CallingConv::C: Out << "CallingConv::C"; break;
284 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
285 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
286 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
287 default: Out << cc; break;
288 }
289 }
290
291 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
292 switch (LT) {
293 case GlobalValue::InternalLinkage:
294 Out << "GlobalValue::InternalLinkage"; break;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000295 case GlobalValue::PrivateLinkage:
296 Out << "GlobalValue::PrivateLinkage"; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000297 case GlobalValue::LinkOnceAnyLinkage:
298 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
299 case GlobalValue::LinkOnceODRLinkage:
300 Out << "GlobalValue::LinkOnceODRLinkage "; break;
301 case GlobalValue::WeakAnyLinkage:
302 Out << "GlobalValue::WeakAnyLinkage"; break;
303 case GlobalValue::WeakODRLinkage:
304 Out << "GlobalValue::WeakODRLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000305 case GlobalValue::AppendingLinkage:
306 Out << "GlobalValue::AppendingLinkage"; break;
307 case GlobalValue::ExternalLinkage:
308 Out << "GlobalValue::ExternalLinkage"; break;
309 case GlobalValue::DLLImportLinkage:
310 Out << "GlobalValue::DLLImportLinkage"; break;
311 case GlobalValue::DLLExportLinkage:
312 Out << "GlobalValue::DLLExportLinkage"; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000313 case GlobalValue::ExternalWeakLinkage:
314 Out << "GlobalValue::ExternalWeakLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000315 case GlobalValue::GhostLinkage:
316 Out << "GlobalValue::GhostLinkage"; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000317 case GlobalValue::CommonLinkage:
318 Out << "GlobalValue::CommonLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000319 }
320 }
321
322 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
323 switch (VisType) {
324 default: assert(0 && "Unknown GVar visibility");
325 case GlobalValue::DefaultVisibility:
326 Out << "GlobalValue::DefaultVisibility";
327 break;
328 case GlobalValue::HiddenVisibility:
329 Out << "GlobalValue::HiddenVisibility";
330 break;
331 case GlobalValue::ProtectedVisibility:
332 Out << "GlobalValue::ProtectedVisibility";
333 break;
334 }
335 }
336
337 // printEscapedString - Print each character of the specified string, escaping
338 // it if it is not printable or if it is an escape char.
339 void CppWriter::printEscapedString(const std::string &Str) {
340 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
341 unsigned char C = Str[i];
342 if (isprint(C) && C != '"' && C != '\\') {
343 Out << C;
344 } else {
345 Out << "\\x"
346 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
347 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
348 }
349 }
350 }
351
352 std::string CppWriter::getCppName(const Type* Ty) {
353 // First, handle the primitive types .. easy
354 if (Ty->isPrimitiveType() || Ty->isInteger()) {
355 switch (Ty->getTypeID()) {
356 case Type::VoidTyID: return "Type::VoidTy";
357 case Type::IntegerTyID: {
358 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
359 return "IntegerType::get(" + utostr(BitWidth) + ")";
360 }
361 case Type::FloatTyID: return "Type::FloatTy";
362 case Type::DoubleTyID: return "Type::DoubleTy";
363 case Type::LabelTyID: return "Type::LabelTy";
364 default:
365 error("Invalid primitive type");
366 break;
367 }
368 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
369 }
370
371 // Now, see if we've seen the type before and return that
372 TypeMap::iterator I = TypeNames.find(Ty);
373 if (I != TypeNames.end())
374 return I->second;
375
376 // Okay, let's build a new name for this type. Start with a prefix
377 const char* prefix = 0;
378 switch (Ty->getTypeID()) {
379 case Type::FunctionTyID: prefix = "FuncTy_"; break;
380 case Type::StructTyID: prefix = "StructTy_"; break;
381 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
382 case Type::PointerTyID: prefix = "PointerTy_"; break;
383 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
384 case Type::VectorTyID: prefix = "VectorTy_"; break;
385 default: prefix = "OtherTy_"; break; // prevent breakage
386 }
387
388 // See if the type has a name in the symboltable and build accordingly
389 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
390 std::string name;
391 if (tName)
392 name = std::string(prefix) + *tName;
393 else
394 name = std::string(prefix) + utostr(uniqueNum++);
395 sanitize(name);
396
397 // Save the name
398 return TypeNames[Ty] = name;
399 }
400
401 void CppWriter::printCppName(const Type* Ty) {
402 printEscapedString(getCppName(Ty));
403 }
404
405 std::string CppWriter::getCppName(const Value* val) {
406 std::string name;
407 ValueMap::iterator I = ValueNames.find(val);
408 if (I != ValueNames.end() && I->first == val)
409 return I->second;
410
411 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
412 name = std::string("gvar_") +
413 getTypePrefix(GV->getType()->getElementType());
414 } else if (isa<Function>(val)) {
415 name = std::string("func_");
416 } else if (const Constant* C = dyn_cast<Constant>(val)) {
417 name = std::string("const_") + getTypePrefix(C->getType());
418 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
419 if (is_inline) {
420 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
421 Function::const_arg_iterator(Arg)) + 1;
422 name = std::string("arg_") + utostr(argNum);
423 NameSet::iterator NI = UsedNames.find(name);
424 if (NI != UsedNames.end())
425 name += std::string("_") + utostr(uniqueNum++);
426 UsedNames.insert(name);
427 return ValueNames[val] = name;
428 } else {
429 name = getTypePrefix(val->getType());
430 }
431 } else {
432 name = getTypePrefix(val->getType());
433 }
434 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
435 sanitize(name);
436 NameSet::iterator NI = UsedNames.find(name);
437 if (NI != UsedNames.end())
438 name += std::string("_") + utostr(uniqueNum++);
439 UsedNames.insert(name);
440 return ValueNames[val] = name;
441 }
442
443 void CppWriter::printCppName(const Value* val) {
444 printEscapedString(getCppName(val));
445 }
446
Devang Patel05988662008-09-25 21:00:45 +0000447 void CppWriter::printAttributes(const AttrListPtr &PAL,
Anton Korobeynikov50276522008-04-23 22:29:24 +0000448 const std::string &name) {
Devang Patel05988662008-09-25 21:00:45 +0000449 Out << "AttrListPtr " << name << "_PAL;";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000450 nl(Out);
451 if (!PAL.isEmpty()) {
452 Out << '{'; in(); nl(Out);
Devang Patel05988662008-09-25 21:00:45 +0000453 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
454 Out << "AttributeWithIndex PAWI;"; nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000455 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000456 unsigned index = PAL.getSlot(i).Index;
Devang Pateleaf42ab2008-09-23 23:03:40 +0000457 Attributes attrs = PAL.getSlot(i).Attrs;
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000458 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
Chris Lattneracca9552009-01-13 07:22:22 +0000459#define HANDLE_ATTR(X) \
460 if (attrs & Attribute::X) \
461 Out << " | Attribute::" #X; \
462 attrs &= ~Attribute::X;
463
464 HANDLE_ATTR(SExt);
465 HANDLE_ATTR(ZExt);
466 HANDLE_ATTR(StructRet);
467 HANDLE_ATTR(InReg);
468 HANDLE_ATTR(NoReturn);
469 HANDLE_ATTR(NoUnwind);
470 HANDLE_ATTR(ByVal);
471 HANDLE_ATTR(NoAlias);
472 HANDLE_ATTR(Nest);
473 HANDLE_ATTR(ReadNone);
474 HANDLE_ATTR(ReadOnly);
475 HANDLE_ATTR(NoCapture);
476#undef HANDLE_ATTR
477 assert(attrs == 0 && "Unhandled attribute!");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000478 Out << ";";
479 nl(Out);
480 Out << "Attrs.push_back(PAWI);";
481 nl(Out);
482 }
Devang Patel05988662008-09-25 21:00:45 +0000483 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000484 nl(Out);
485 out(); nl(Out);
486 Out << '}'; nl(Out);
487 }
488 }
489
490 bool CppWriter::printTypeInternal(const Type* Ty) {
491 // We don't print definitions for primitive types
492 if (Ty->isPrimitiveType() || Ty->isInteger())
493 return false;
494
495 // If we already defined this type, we don't need to define it again.
496 if (DefinedTypes.find(Ty) != DefinedTypes.end())
497 return false;
498
499 // Everything below needs the name for the type so get it now.
500 std::string typeName(getCppName(Ty));
501
502 // Search the type stack for recursion. If we find it, then generate this
503 // as an OpaqueType, but make sure not to do this multiple times because
504 // the type could appear in multiple places on the stack. Once the opaque
505 // definition is issued, it must not be re-issued. Consequently we have to
506 // check the UnresolvedTypes list as well.
507 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
508 Ty);
509 if (TI != TypeStack.end()) {
510 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
511 if (I == UnresolvedTypes.end()) {
512 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
513 nl(Out);
514 UnresolvedTypes[Ty] = typeName;
515 }
516 return true;
517 }
518
519 // We're going to print a derived type which, by definition, contains other
520 // types. So, push this one we're printing onto the type stack to assist with
521 // recursive definitions.
522 TypeStack.push_back(Ty);
523
524 // Print the type definition
525 switch (Ty->getTypeID()) {
526 case Type::FunctionTyID: {
527 const FunctionType* FT = cast<FunctionType>(Ty);
528 Out << "std::vector<const Type*>" << typeName << "_args;";
529 nl(Out);
530 FunctionType::param_iterator PI = FT->param_begin();
531 FunctionType::param_iterator PE = FT->param_end();
532 for (; PI != PE; ++PI) {
533 const Type* argTy = static_cast<const Type*>(*PI);
534 bool isForward = printTypeInternal(argTy);
535 std::string argName(getCppName(argTy));
536 Out << typeName << "_args.push_back(" << argName;
537 if (isForward)
538 Out << "_fwd";
539 Out << ");";
540 nl(Out);
541 }
542 bool isForward = printTypeInternal(FT->getReturnType());
543 std::string retTypeName(getCppName(FT->getReturnType()));
544 Out << "FunctionType* " << typeName << " = FunctionType::get(";
545 in(); nl(Out) << "/*Result=*/" << retTypeName;
546 if (isForward)
547 Out << "_fwd";
548 Out << ",";
549 nl(Out) << "/*Params=*/" << typeName << "_args,";
550 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
551 out();
552 nl(Out);
553 break;
554 }
555 case Type::StructTyID: {
556 const StructType* ST = cast<StructType>(Ty);
557 Out << "std::vector<const Type*>" << typeName << "_fields;";
558 nl(Out);
559 StructType::element_iterator EI = ST->element_begin();
560 StructType::element_iterator EE = ST->element_end();
561 for (; EI != EE; ++EI) {
562 const Type* fieldTy = static_cast<const Type*>(*EI);
563 bool isForward = printTypeInternal(fieldTy);
564 std::string fieldName(getCppName(fieldTy));
565 Out << typeName << "_fields.push_back(" << fieldName;
566 if (isForward)
567 Out << "_fwd";
568 Out << ");";
569 nl(Out);
570 }
571 Out << "StructType* " << typeName << " = StructType::get("
572 << typeName << "_fields, /*isPacked=*/"
573 << (ST->isPacked() ? "true" : "false") << ");";
574 nl(Out);
575 break;
576 }
577 case Type::ArrayTyID: {
578 const ArrayType* AT = cast<ArrayType>(Ty);
579 const Type* ET = AT->getElementType();
580 bool isForward = printTypeInternal(ET);
581 std::string elemName(getCppName(ET));
582 Out << "ArrayType* " << typeName << " = ArrayType::get("
583 << elemName << (isForward ? "_fwd" : "")
584 << ", " << utostr(AT->getNumElements()) << ");";
585 nl(Out);
586 break;
587 }
588 case Type::PointerTyID: {
589 const PointerType* PT = cast<PointerType>(Ty);
590 const Type* ET = PT->getElementType();
591 bool isForward = printTypeInternal(ET);
592 std::string elemName(getCppName(ET));
593 Out << "PointerType* " << typeName << " = PointerType::get("
594 << elemName << (isForward ? "_fwd" : "")
595 << ", " << utostr(PT->getAddressSpace()) << ");";
596 nl(Out);
597 break;
598 }
599 case Type::VectorTyID: {
600 const VectorType* PT = cast<VectorType>(Ty);
601 const Type* ET = PT->getElementType();
602 bool isForward = printTypeInternal(ET);
603 std::string elemName(getCppName(ET));
604 Out << "VectorType* " << typeName << " = VectorType::get("
605 << elemName << (isForward ? "_fwd" : "")
606 << ", " << utostr(PT->getNumElements()) << ");";
607 nl(Out);
608 break;
609 }
610 case Type::OpaqueTyID: {
611 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
612 nl(Out);
613 break;
614 }
615 default:
616 error("Invalid TypeID");
617 }
618
619 // If the type had a name, make sure we recreate it.
620 const std::string* progTypeName =
621 findTypeName(TheModule->getTypeSymbolTable(),Ty);
622 if (progTypeName) {
623 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
624 << typeName << ");";
625 nl(Out);
626 }
627
628 // Pop us off the type stack
629 TypeStack.pop_back();
630
631 // Indicate that this type is now defined.
632 DefinedTypes.insert(Ty);
633
634 // Early resolve as many unresolved types as possible. Search the unresolved
635 // types map for the type we just printed. Now that its definition is complete
636 // we can resolve any previous references to it. This prevents a cascade of
637 // unresolved types.
638 TypeMap::iterator I = UnresolvedTypes.find(Ty);
639 if (I != UnresolvedTypes.end()) {
640 Out << "cast<OpaqueType>(" << I->second
641 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
642 nl(Out);
643 Out << I->second << " = cast<";
644 switch (Ty->getTypeID()) {
645 case Type::FunctionTyID: Out << "FunctionType"; break;
646 case Type::ArrayTyID: Out << "ArrayType"; break;
647 case Type::StructTyID: Out << "StructType"; break;
648 case Type::VectorTyID: Out << "VectorType"; break;
649 case Type::PointerTyID: Out << "PointerType"; break;
650 case Type::OpaqueTyID: Out << "OpaqueType"; break;
651 default: Out << "NoSuchDerivedType"; break;
652 }
653 Out << ">(" << I->second << "_fwd.get());";
654 nl(Out); nl(Out);
655 UnresolvedTypes.erase(I);
656 }
657
658 // Finally, separate the type definition from other with a newline.
659 nl(Out);
660
661 // We weren't a recursive type
662 return false;
663 }
664
665 // Prints a type definition. Returns true if it could not resolve all the
666 // types in the definition but had to use a forward reference.
667 void CppWriter::printType(const Type* Ty) {
668 assert(TypeStack.empty());
669 TypeStack.clear();
670 printTypeInternal(Ty);
671 assert(TypeStack.empty());
672 }
673
674 void CppWriter::printTypes(const Module* M) {
675 // Walk the symbol table and print out all its types
676 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
677 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
678 TI != TE; ++TI) {
679
680 // For primitive types and types already defined, just add a name
681 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
682 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
683 TNI != TypeNames.end()) {
684 Out << "mod->addTypeName(\"";
685 printEscapedString(TI->first);
686 Out << "\", " << getCppName(TI->second) << ");";
687 nl(Out);
688 // For everything else, define the type
689 } else {
690 printType(TI->second);
691 }
692 }
693
694 // Add all of the global variables to the value table...
695 for (Module::const_global_iterator I = TheModule->global_begin(),
696 E = TheModule->global_end(); I != E; ++I) {
697 if (I->hasInitializer())
698 printType(I->getInitializer()->getType());
699 printType(I->getType());
700 }
701
702 // Add all the functions to the table
703 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
704 FI != FE; ++FI) {
705 printType(FI->getReturnType());
706 printType(FI->getFunctionType());
707 // Add all the function arguments
708 for (Function::const_arg_iterator AI = FI->arg_begin(),
709 AE = FI->arg_end(); AI != AE; ++AI) {
710 printType(AI->getType());
711 }
712
713 // Add all of the basic blocks and instructions
714 for (Function::const_iterator BB = FI->begin(),
715 E = FI->end(); BB != E; ++BB) {
716 printType(BB->getType());
717 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
718 ++I) {
719 printType(I->getType());
720 for (unsigned i = 0; i < I->getNumOperands(); ++i)
721 printType(I->getOperand(i)->getType());
722 }
723 }
724 }
725 }
726
727
728 // printConstant - Print out a constant pool entry...
729 void CppWriter::printConstant(const Constant *CV) {
730 // First, if the constant is actually a GlobalValue (variable or function)
731 // or its already in the constant list then we've printed it already and we
732 // can just return.
733 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
734 return;
735
736 std::string constName(getCppName(CV));
737 std::string typeName(getCppName(CV->getType()));
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000738
Anton Korobeynikov50276522008-04-23 22:29:24 +0000739 if (isa<GlobalValue>(CV)) {
740 // Skip variables and functions, we emit them elsewhere
741 return;
742 }
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000743
Anton Korobeynikov50276522008-04-23 22:29:24 +0000744 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Anton Korobeynikov70053c32008-08-18 20:03:45 +0000745 std::string constValue = CI->getValue().toString(10, true);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000746 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
Chris Lattnerfad86b02008-08-17 07:19:36 +0000747 << cast<IntegerType>(CI->getType())->getBitWidth() << ", \""
Anton Korobeynikov70053c32008-08-18 20:03:45 +0000748 << constValue << "\", " << constValue.length() << ", 10));";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000749 } else if (isa<ConstantAggregateZero>(CV)) {
750 Out << "ConstantAggregateZero* " << constName
751 << " = ConstantAggregateZero::get(" << typeName << ");";
752 } else if (isa<ConstantPointerNull>(CV)) {
753 Out << "ConstantPointerNull* " << constName
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000754 << " = ConstantPointerNull::get(" << typeName << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000755 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
756 Out << "ConstantFP* " << constName << " = ";
757 printCFP(CFP);
758 Out << ";";
759 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
760 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
761 Out << "Constant* " << constName << " = ConstantArray::get(\"";
762 std::string tmp = CA->getAsString();
763 bool nullTerminate = false;
764 if (tmp[tmp.length()-1] == 0) {
765 tmp.erase(tmp.length()-1);
766 nullTerminate = true;
767 }
768 printEscapedString(tmp);
769 // Determine if we want null termination or not.
770 if (nullTerminate)
771 Out << "\", true"; // Indicate that the null terminator should be
772 // added.
773 else
774 Out << "\", false";// No null terminator
775 Out << ");";
776 } else {
777 Out << "std::vector<Constant*> " << constName << "_elems;";
778 nl(Out);
779 unsigned N = CA->getNumOperands();
780 for (unsigned i = 0; i < N; ++i) {
781 printConstant(CA->getOperand(i)); // recurse to print operands
782 Out << constName << "_elems.push_back("
783 << getCppName(CA->getOperand(i)) << ");";
784 nl(Out);
785 }
786 Out << "Constant* " << constName << " = ConstantArray::get("
787 << typeName << ", " << constName << "_elems);";
788 }
789 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
790 Out << "std::vector<Constant*> " << constName << "_fields;";
791 nl(Out);
792 unsigned N = CS->getNumOperands();
793 for (unsigned i = 0; i < N; i++) {
794 printConstant(CS->getOperand(i));
795 Out << constName << "_fields.push_back("
796 << getCppName(CS->getOperand(i)) << ");";
797 nl(Out);
798 }
799 Out << "Constant* " << constName << " = ConstantStruct::get("
800 << typeName << ", " << constName << "_fields);";
801 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
802 Out << "std::vector<Constant*> " << constName << "_elems;";
803 nl(Out);
804 unsigned N = CP->getNumOperands();
805 for (unsigned i = 0; i < N; ++i) {
806 printConstant(CP->getOperand(i));
807 Out << constName << "_elems.push_back("
808 << getCppName(CP->getOperand(i)) << ");";
809 nl(Out);
810 }
811 Out << "Constant* " << constName << " = ConstantVector::get("
812 << typeName << ", " << constName << "_elems);";
813 } else if (isa<UndefValue>(CV)) {
814 Out << "UndefValue* " << constName << " = UndefValue::get("
815 << typeName << ");";
816 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
817 if (CE->getOpcode() == Instruction::GetElementPtr) {
818 Out << "std::vector<Constant*> " << constName << "_indices;";
819 nl(Out);
820 printConstant(CE->getOperand(0));
821 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
822 printConstant(CE->getOperand(i));
823 Out << constName << "_indices.push_back("
824 << getCppName(CE->getOperand(i)) << ");";
825 nl(Out);
826 }
827 Out << "Constant* " << constName
828 << " = ConstantExpr::getGetElementPtr("
829 << getCppName(CE->getOperand(0)) << ", "
830 << "&" << constName << "_indices[0], "
831 << constName << "_indices.size()"
832 << " );";
833 } else if (CE->isCast()) {
834 printConstant(CE->getOperand(0));
835 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
836 switch (CE->getOpcode()) {
837 default: assert(0 && "Invalid cast opcode");
838 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
839 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
840 case Instruction::SExt: Out << "Instruction::SExt"; break;
841 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
842 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
843 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
844 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
845 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
846 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
847 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
848 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
849 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
850 }
851 Out << ", " << getCppName(CE->getOperand(0)) << ", "
852 << getCppName(CE->getType()) << ");";
853 } else {
854 unsigned N = CE->getNumOperands();
855 for (unsigned i = 0; i < N; ++i ) {
856 printConstant(CE->getOperand(i));
857 }
858 Out << "Constant* " << constName << " = ConstantExpr::";
859 switch (CE->getOpcode()) {
860 case Instruction::Add: Out << "getAdd("; break;
861 case Instruction::Sub: Out << "getSub("; break;
862 case Instruction::Mul: Out << "getMul("; break;
863 case Instruction::UDiv: Out << "getUDiv("; break;
864 case Instruction::SDiv: Out << "getSDiv("; break;
865 case Instruction::FDiv: Out << "getFDiv("; break;
866 case Instruction::URem: Out << "getURem("; break;
867 case Instruction::SRem: Out << "getSRem("; break;
868 case Instruction::FRem: Out << "getFRem("; break;
869 case Instruction::And: Out << "getAnd("; break;
870 case Instruction::Or: Out << "getOr("; break;
871 case Instruction::Xor: Out << "getXor("; break;
872 case Instruction::ICmp:
873 Out << "getICmp(ICmpInst::ICMP_";
874 switch (CE->getPredicate()) {
875 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
876 case ICmpInst::ICMP_NE: Out << "NE"; break;
877 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
878 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
879 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
880 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
881 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
882 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
883 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
884 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
885 default: error("Invalid ICmp Predicate");
886 }
887 break;
888 case Instruction::FCmp:
889 Out << "getFCmp(FCmpInst::FCMP_";
890 switch (CE->getPredicate()) {
891 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
892 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
893 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
894 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
895 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
896 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
897 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
898 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
899 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
900 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
901 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
902 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
903 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
904 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
905 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
906 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
907 default: error("Invalid FCmp Predicate");
908 }
909 break;
910 case Instruction::Shl: Out << "getShl("; break;
911 case Instruction::LShr: Out << "getLShr("; break;
912 case Instruction::AShr: Out << "getAShr("; break;
913 case Instruction::Select: Out << "getSelect("; break;
914 case Instruction::ExtractElement: Out << "getExtractElement("; break;
915 case Instruction::InsertElement: Out << "getInsertElement("; break;
916 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
917 default:
918 error("Invalid constant expression");
919 break;
920 }
921 Out << getCppName(CE->getOperand(0));
922 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
923 Out << ", " << getCppName(CE->getOperand(i));
924 Out << ");";
925 }
926 } else {
927 error("Bad Constant");
928 Out << "Constant* " << constName << " = 0; ";
929 }
930 nl(Out);
931 }
932
933 void CppWriter::printConstants(const Module* M) {
934 // Traverse all the global variables looking for constant initializers
935 for (Module::const_global_iterator I = TheModule->global_begin(),
936 E = TheModule->global_end(); I != E; ++I)
937 if (I->hasInitializer())
938 printConstant(I->getInitializer());
939
940 // Traverse the LLVM functions looking for constants
941 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
942 FI != FE; ++FI) {
943 // Add all of the basic blocks and instructions
944 for (Function::const_iterator BB = FI->begin(),
945 E = FI->end(); BB != E; ++BB) {
946 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
947 ++I) {
948 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
949 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
950 printConstant(C);
951 }
952 }
953 }
954 }
955 }
956 }
957
958 void CppWriter::printVariableUses(const GlobalVariable *GV) {
959 nl(Out) << "// Type Definitions";
960 nl(Out);
961 printType(GV->getType());
962 if (GV->hasInitializer()) {
963 Constant* Init = GV->getInitializer();
964 printType(Init->getType());
965 if (Function* F = dyn_cast<Function>(Init)) {
966 nl(Out)<< "/ Function Declarations"; nl(Out);
967 printFunctionHead(F);
968 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
969 nl(Out) << "// Global Variable Declarations"; nl(Out);
970 printVariableHead(gv);
971 } else {
972 nl(Out) << "// Constant Definitions"; nl(Out);
973 printConstant(gv);
974 }
975 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
976 nl(Out) << "// Global Variable Definitions"; nl(Out);
977 printVariableBody(gv);
978 }
979 }
980 }
981
982 void CppWriter::printVariableHead(const GlobalVariable *GV) {
983 nl(Out) << "GlobalVariable* " << getCppName(GV);
984 if (is_inline) {
985 Out << " = mod->getGlobalVariable(";
986 printEscapedString(GV->getName());
987 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
988 nl(Out) << "if (!" << getCppName(GV) << ") {";
989 in(); nl(Out) << getCppName(GV);
990 }
991 Out << " = new GlobalVariable(";
992 nl(Out) << "/*Type=*/";
993 printCppName(GV->getType()->getElementType());
994 Out << ",";
995 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
996 Out << ",";
997 nl(Out) << "/*Linkage=*/";
998 printLinkageType(GV->getLinkage());
999 Out << ",";
1000 nl(Out) << "/*Initializer=*/0, ";
1001 if (GV->hasInitializer()) {
1002 Out << "// has initializer, specified below";
1003 }
1004 nl(Out) << "/*Name=*/\"";
1005 printEscapedString(GV->getName());
1006 Out << "\",";
1007 nl(Out) << "mod);";
1008 nl(Out);
1009
1010 if (GV->hasSection()) {
1011 printCppName(GV);
1012 Out << "->setSection(\"";
1013 printEscapedString(GV->getSection());
1014 Out << "\");";
1015 nl(Out);
1016 }
1017 if (GV->getAlignment()) {
1018 printCppName(GV);
1019 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1020 nl(Out);
1021 }
1022 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1023 printCppName(GV);
1024 Out << "->setVisibility(";
1025 printVisibilityType(GV->getVisibility());
1026 Out << ");";
1027 nl(Out);
1028 }
1029 if (is_inline) {
1030 out(); Out << "}"; nl(Out);
1031 }
1032 }
1033
1034 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1035 if (GV->hasInitializer()) {
1036 printCppName(GV);
1037 Out << "->setInitializer(";
1038 Out << getCppName(GV->getInitializer()) << ");";
1039 nl(Out);
1040 }
1041 }
1042
1043 std::string CppWriter::getOpName(Value* V) {
1044 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1045 return getCppName(V);
1046
1047 // See if its alread in the map of forward references, if so just return the
1048 // name we already set up for it
1049 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1050 if (I != ForwardRefs.end())
1051 return I->second;
1052
1053 // This is a new forward reference. Generate a unique name for it
1054 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1055
1056 // Yes, this is a hack. An Argument is the smallest instantiable value that
1057 // we can make as a placeholder for the real value. We'll replace these
1058 // Argument instances later.
1059 Out << "Argument* " << result << " = new Argument("
1060 << getCppName(V->getType()) << ");";
1061 nl(Out);
1062 ForwardRefs[V] = result;
1063 return result;
1064 }
1065
1066 // printInstruction - This member is called for each Instruction in a function.
1067 void CppWriter::printInstruction(const Instruction *I,
1068 const std::string& bbname) {
1069 std::string iName(getCppName(I));
1070
1071 // Before we emit this instruction, we need to take care of generating any
1072 // forward references. So, we get the names of all the operands in advance
1073 std::string* opNames = new std::string[I->getNumOperands()];
1074 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1075 opNames[i] = getOpName(I->getOperand(i));
1076 }
1077
1078 switch (I->getOpcode()) {
Dan Gohman26825a82008-06-09 14:09:13 +00001079 default:
1080 error("Invalid instruction");
1081 break;
1082
Anton Korobeynikov50276522008-04-23 22:29:24 +00001083 case Instruction::Ret: {
1084 const ReturnInst* ret = cast<ReturnInst>(I);
1085 Out << "ReturnInst::Create("
1086 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1087 break;
1088 }
1089 case Instruction::Br: {
1090 const BranchInst* br = cast<BranchInst>(I);
1091 Out << "BranchInst::Create(" ;
1092 if (br->getNumOperands() == 3 ) {
1093 Out << opNames[0] << ", "
1094 << opNames[1] << ", "
1095 << opNames[2] << ", ";
1096
1097 } else if (br->getNumOperands() == 1) {
1098 Out << opNames[0] << ", ";
1099 } else {
1100 error("Branch with 2 operands?");
1101 }
1102 Out << bbname << ");";
1103 break;
1104 }
1105 case Instruction::Switch: {
1106 const SwitchInst* sw = cast<SwitchInst>(I);
1107 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1108 << opNames[0] << ", "
1109 << opNames[1] << ", "
1110 << sw->getNumCases() << ", " << bbname << ");";
1111 nl(Out);
1112 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1113 Out << iName << "->addCase("
1114 << opNames[i] << ", "
1115 << opNames[i+1] << ");";
1116 nl(Out);
1117 }
1118 break;
1119 }
1120 case Instruction::Invoke: {
1121 const InvokeInst* inv = cast<InvokeInst>(I);
1122 Out << "std::vector<Value*> " << iName << "_params;";
1123 nl(Out);
1124 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1125 Out << iName << "_params.push_back("
1126 << opNames[i] << ");";
1127 nl(Out);
1128 }
1129 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1130 << opNames[0] << ", "
1131 << opNames[1] << ", "
1132 << opNames[2] << ", "
1133 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1134 printEscapedString(inv->getName());
1135 Out << "\", " << bbname << ");";
1136 nl(Out) << iName << "->setCallingConv(";
1137 printCallingConv(inv->getCallingConv());
1138 Out << ");";
Devang Patel05988662008-09-25 21:00:45 +00001139 printAttributes(inv->getAttributes(), iName);
1140 Out << iName << "->setAttributes(" << iName << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001141 nl(Out);
1142 break;
1143 }
1144 case Instruction::Unwind: {
1145 Out << "new UnwindInst("
1146 << bbname << ");";
1147 break;
1148 }
1149 case Instruction::Unreachable:{
1150 Out << "new UnreachableInst("
1151 << bbname << ");";
1152 break;
1153 }
1154 case Instruction::Add:
1155 case Instruction::Sub:
1156 case Instruction::Mul:
1157 case Instruction::UDiv:
1158 case Instruction::SDiv:
1159 case Instruction::FDiv:
1160 case Instruction::URem:
1161 case Instruction::SRem:
1162 case Instruction::FRem:
1163 case Instruction::And:
1164 case Instruction::Or:
1165 case Instruction::Xor:
1166 case Instruction::Shl:
1167 case Instruction::LShr:
1168 case Instruction::AShr:{
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001169 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001170 switch (I->getOpcode()) {
1171 case Instruction::Add: Out << "Instruction::Add"; break;
1172 case Instruction::Sub: Out << "Instruction::Sub"; break;
1173 case Instruction::Mul: Out << "Instruction::Mul"; break;
1174 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1175 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1176 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1177 case Instruction::URem:Out << "Instruction::URem"; break;
1178 case Instruction::SRem:Out << "Instruction::SRem"; break;
1179 case Instruction::FRem:Out << "Instruction::FRem"; break;
1180 case Instruction::And: Out << "Instruction::And"; break;
1181 case Instruction::Or: Out << "Instruction::Or"; break;
1182 case Instruction::Xor: Out << "Instruction::Xor"; break;
1183 case Instruction::Shl: Out << "Instruction::Shl"; break;
1184 case Instruction::LShr:Out << "Instruction::LShr"; break;
1185 case Instruction::AShr:Out << "Instruction::AShr"; break;
1186 default: Out << "Instruction::BadOpCode"; break;
1187 }
1188 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1189 printEscapedString(I->getName());
1190 Out << "\", " << bbname << ");";
1191 break;
1192 }
1193 case Instruction::FCmp: {
1194 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1195 switch (cast<FCmpInst>(I)->getPredicate()) {
1196 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1197 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1198 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1199 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1200 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1201 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1202 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1203 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1204 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1205 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1206 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1207 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1208 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1209 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1210 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1211 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1212 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1213 }
1214 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1215 printEscapedString(I->getName());
1216 Out << "\", " << bbname << ");";
1217 break;
1218 }
1219 case Instruction::ICmp: {
1220 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1221 switch (cast<ICmpInst>(I)->getPredicate()) {
1222 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1223 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1224 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1225 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1226 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1227 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1228 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1229 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1230 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1231 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1232 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1233 }
1234 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1235 printEscapedString(I->getName());
1236 Out << "\", " << bbname << ");";
1237 break;
1238 }
1239 case Instruction::Malloc: {
1240 const MallocInst* mallocI = cast<MallocInst>(I);
1241 Out << "MallocInst* " << iName << " = new MallocInst("
1242 << getCppName(mallocI->getAllocatedType()) << ", ";
1243 if (mallocI->isArrayAllocation())
1244 Out << opNames[0] << ", " ;
1245 Out << "\"";
1246 printEscapedString(mallocI->getName());
1247 Out << "\", " << bbname << ");";
1248 if (mallocI->getAlignment())
1249 nl(Out) << iName << "->setAlignment("
1250 << mallocI->getAlignment() << ");";
1251 break;
1252 }
1253 case Instruction::Free: {
1254 Out << "FreeInst* " << iName << " = new FreeInst("
1255 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1256 break;
1257 }
1258 case Instruction::Alloca: {
1259 const AllocaInst* allocaI = cast<AllocaInst>(I);
1260 Out << "AllocaInst* " << iName << " = new AllocaInst("
1261 << getCppName(allocaI->getAllocatedType()) << ", ";
1262 if (allocaI->isArrayAllocation())
1263 Out << opNames[0] << ", ";
1264 Out << "\"";
1265 printEscapedString(allocaI->getName());
1266 Out << "\", " << bbname << ");";
1267 if (allocaI->getAlignment())
1268 nl(Out) << iName << "->setAlignment("
1269 << allocaI->getAlignment() << ");";
1270 break;
1271 }
1272 case Instruction::Load:{
1273 const LoadInst* load = cast<LoadInst>(I);
1274 Out << "LoadInst* " << iName << " = new LoadInst("
1275 << opNames[0] << ", \"";
1276 printEscapedString(load->getName());
1277 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1278 << ", " << bbname << ");";
1279 break;
1280 }
1281 case Instruction::Store: {
1282 const StoreInst* store = cast<StoreInst>(I);
Anton Korobeynikovb0714db2008-11-09 02:54:13 +00001283 Out << " new StoreInst("
Anton Korobeynikov50276522008-04-23 22:29:24 +00001284 << opNames[0] << ", "
1285 << opNames[1] << ", "
1286 << (store->isVolatile() ? "true" : "false")
1287 << ", " << bbname << ");";
1288 break;
1289 }
1290 case Instruction::GetElementPtr: {
1291 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1292 if (gep->getNumOperands() <= 2) {
1293 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1294 << opNames[0];
1295 if (gep->getNumOperands() == 2)
1296 Out << ", " << opNames[1];
1297 } else {
1298 Out << "std::vector<Value*> " << iName << "_indices;";
1299 nl(Out);
1300 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1301 Out << iName << "_indices.push_back("
1302 << opNames[i] << ");";
1303 nl(Out);
1304 }
1305 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1306 << opNames[0] << ", " << iName << "_indices.begin(), "
1307 << iName << "_indices.end()";
1308 }
1309 Out << ", \"";
1310 printEscapedString(gep->getName());
1311 Out << "\", " << bbname << ");";
1312 break;
1313 }
1314 case Instruction::PHI: {
1315 const PHINode* phi = cast<PHINode>(I);
1316
1317 Out << "PHINode* " << iName << " = PHINode::Create("
1318 << getCppName(phi->getType()) << ", \"";
1319 printEscapedString(phi->getName());
1320 Out << "\", " << bbname << ");";
1321 nl(Out) << iName << "->reserveOperandSpace("
1322 << phi->getNumIncomingValues()
1323 << ");";
1324 nl(Out);
1325 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1326 Out << iName << "->addIncoming("
1327 << opNames[i] << ", " << opNames[i+1] << ");";
1328 nl(Out);
1329 }
1330 break;
1331 }
1332 case Instruction::Trunc:
1333 case Instruction::ZExt:
1334 case Instruction::SExt:
1335 case Instruction::FPTrunc:
1336 case Instruction::FPExt:
1337 case Instruction::FPToUI:
1338 case Instruction::FPToSI:
1339 case Instruction::UIToFP:
1340 case Instruction::SIToFP:
1341 case Instruction::PtrToInt:
1342 case Instruction::IntToPtr:
1343 case Instruction::BitCast: {
1344 const CastInst* cst = cast<CastInst>(I);
1345 Out << "CastInst* " << iName << " = new ";
1346 switch (I->getOpcode()) {
1347 case Instruction::Trunc: Out << "TruncInst"; break;
1348 case Instruction::ZExt: Out << "ZExtInst"; break;
1349 case Instruction::SExt: Out << "SExtInst"; break;
1350 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1351 case Instruction::FPExt: Out << "FPExtInst"; break;
1352 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1353 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1354 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1355 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1356 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1357 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1358 case Instruction::BitCast: Out << "BitCastInst"; break;
1359 default: assert(!"Unreachable"); break;
1360 }
1361 Out << "(" << opNames[0] << ", "
1362 << getCppName(cst->getType()) << ", \"";
1363 printEscapedString(cst->getName());
1364 Out << "\", " << bbname << ");";
1365 break;
1366 }
1367 case Instruction::Call:{
1368 const CallInst* call = cast<CallInst>(I);
1369 if (InlineAsm* ila = dyn_cast<InlineAsm>(call->getOperand(0))) {
1370 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1371 << getCppName(ila->getFunctionType()) << ", \""
1372 << ila->getAsmString() << "\", \""
1373 << ila->getConstraintString() << "\","
1374 << (ila->hasSideEffects() ? "true" : "false") << ");";
1375 nl(Out);
1376 }
1377 if (call->getNumOperands() > 2) {
1378 Out << "std::vector<Value*> " << iName << "_params;";
1379 nl(Out);
1380 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1381 Out << iName << "_params.push_back(" << opNames[i] << ");";
1382 nl(Out);
1383 }
1384 Out << "CallInst* " << iName << " = CallInst::Create("
1385 << opNames[0] << ", " << iName << "_params.begin(), "
1386 << iName << "_params.end(), \"";
1387 } else if (call->getNumOperands() == 2) {
1388 Out << "CallInst* " << iName << " = CallInst::Create("
1389 << opNames[0] << ", " << opNames[1] << ", \"";
1390 } else {
1391 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1392 << ", \"";
1393 }
1394 printEscapedString(call->getName());
1395 Out << "\", " << bbname << ");";
1396 nl(Out) << iName << "->setCallingConv(";
1397 printCallingConv(call->getCallingConv());
1398 Out << ");";
1399 nl(Out) << iName << "->setTailCall("
1400 << (call->isTailCall() ? "true":"false");
1401 Out << ");";
Devang Patel05988662008-09-25 21:00:45 +00001402 printAttributes(call->getAttributes(), iName);
1403 Out << iName << "->setAttributes(" << iName << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001404 nl(Out);
1405 break;
1406 }
1407 case Instruction::Select: {
1408 const SelectInst* sel = cast<SelectInst>(I);
1409 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1410 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1411 printEscapedString(sel->getName());
1412 Out << "\", " << bbname << ");";
1413 break;
1414 }
1415 case Instruction::UserOp1:
1416 /// FALL THROUGH
1417 case Instruction::UserOp2: {
1418 /// FIXME: What should be done here?
1419 break;
1420 }
1421 case Instruction::VAArg: {
1422 const VAArgInst* va = cast<VAArgInst>(I);
1423 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1424 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1425 printEscapedString(va->getName());
1426 Out << "\", " << bbname << ");";
1427 break;
1428 }
1429 case Instruction::ExtractElement: {
1430 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1431 Out << "ExtractElementInst* " << getCppName(eei)
1432 << " = new ExtractElementInst(" << opNames[0]
1433 << ", " << opNames[1] << ", \"";
1434 printEscapedString(eei->getName());
1435 Out << "\", " << bbname << ");";
1436 break;
1437 }
1438 case Instruction::InsertElement: {
1439 const InsertElementInst* iei = cast<InsertElementInst>(I);
1440 Out << "InsertElementInst* " << getCppName(iei)
1441 << " = InsertElementInst::Create(" << opNames[0]
1442 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1443 printEscapedString(iei->getName());
1444 Out << "\", " << bbname << ");";
1445 break;
1446 }
1447 case Instruction::ShuffleVector: {
1448 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1449 Out << "ShuffleVectorInst* " << getCppName(svi)
1450 << " = new ShuffleVectorInst(" << opNames[0]
1451 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1452 printEscapedString(svi->getName());
1453 Out << "\", " << bbname << ");";
1454 break;
1455 }
Dan Gohman75146a62008-06-09 14:12:10 +00001456 case Instruction::ExtractValue: {
1457 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1458 Out << "std::vector<unsigned> " << iName << "_indices;";
1459 nl(Out);
1460 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1461 Out << iName << "_indices.push_back("
1462 << evi->idx_begin()[i] << ");";
1463 nl(Out);
1464 }
1465 Out << "ExtractValueInst* " << getCppName(evi)
1466 << " = ExtractValueInst::Create(" << opNames[0]
1467 << ", "
1468 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1469 printEscapedString(evi->getName());
1470 Out << "\", " << bbname << ");";
1471 break;
1472 }
1473 case Instruction::InsertValue: {
1474 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1475 Out << "std::vector<unsigned> " << iName << "_indices;";
1476 nl(Out);
1477 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1478 Out << iName << "_indices.push_back("
1479 << ivi->idx_begin()[i] << ");";
1480 nl(Out);
1481 }
1482 Out << "InsertValueInst* " << getCppName(ivi)
1483 << " = InsertValueInst::Create(" << opNames[0]
1484 << ", " << opNames[1] << ", "
1485 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1486 printEscapedString(ivi->getName());
1487 Out << "\", " << bbname << ");";
1488 break;
1489 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001490 }
1491 DefinedValues.insert(I);
1492 nl(Out);
1493 delete [] opNames;
1494}
1495
1496 // Print out the types, constants and declarations needed by one function
1497 void CppWriter::printFunctionUses(const Function* F) {
1498 nl(Out) << "// Type Definitions"; nl(Out);
1499 if (!is_inline) {
1500 // Print the function's return type
1501 printType(F->getReturnType());
1502
1503 // Print the function's function type
1504 printType(F->getFunctionType());
1505
1506 // Print the types of each of the function's arguments
1507 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1508 AI != AE; ++AI) {
1509 printType(AI->getType());
1510 }
1511 }
1512
1513 // Print type definitions for every type referenced by an instruction and
1514 // make a note of any global values or constants that are referenced
1515 SmallPtrSet<GlobalValue*,64> gvs;
1516 SmallPtrSet<Constant*,64> consts;
1517 for (Function::const_iterator BB = F->begin(), BE = F->end();
1518 BB != BE; ++BB){
1519 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1520 I != E; ++I) {
1521 // Print the type of the instruction itself
1522 printType(I->getType());
1523
1524 // Print the type of each of the instruction's operands
1525 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1526 Value* operand = I->getOperand(i);
1527 printType(operand->getType());
1528
1529 // If the operand references a GVal or Constant, make a note of it
1530 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1531 gvs.insert(GV);
1532 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1533 if (GVar->hasInitializer())
1534 consts.insert(GVar->getInitializer());
1535 } else if (Constant* C = dyn_cast<Constant>(operand))
1536 consts.insert(C);
1537 }
1538 }
1539 }
1540
1541 // Print the function declarations for any functions encountered
1542 nl(Out) << "// Function Declarations"; nl(Out);
1543 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1544 I != E; ++I) {
1545 if (Function* Fun = dyn_cast<Function>(*I)) {
1546 if (!is_inline || Fun != F)
1547 printFunctionHead(Fun);
1548 }
1549 }
1550
1551 // Print the global variable declarations for any variables encountered
1552 nl(Out) << "// Global Variable Declarations"; nl(Out);
1553 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1554 I != E; ++I) {
1555 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1556 printVariableHead(F);
1557 }
1558
1559 // Print the constants found
1560 nl(Out) << "// Constant Definitions"; nl(Out);
1561 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1562 E = consts.end(); I != E; ++I) {
1563 printConstant(*I);
1564 }
1565
1566 // Process the global variables definitions now that all the constants have
1567 // been emitted. These definitions just couple the gvars with their constant
1568 // initializers.
1569 nl(Out) << "// Global Variable Definitions"; nl(Out);
1570 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1571 I != E; ++I) {
1572 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1573 printVariableBody(GV);
1574 }
1575 }
1576
1577 void CppWriter::printFunctionHead(const Function* F) {
1578 nl(Out) << "Function* " << getCppName(F);
1579 if (is_inline) {
1580 Out << " = mod->getFunction(\"";
1581 printEscapedString(F->getName());
1582 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1583 nl(Out) << "if (!" << getCppName(F) << ") {";
1584 nl(Out) << getCppName(F);
1585 }
1586 Out<< " = Function::Create(";
1587 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1588 nl(Out) << "/*Linkage=*/";
1589 printLinkageType(F->getLinkage());
1590 Out << ",";
1591 nl(Out) << "/*Name=*/\"";
1592 printEscapedString(F->getName());
1593 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1594 nl(Out,-1);
1595 printCppName(F);
1596 Out << "->setCallingConv(";
1597 printCallingConv(F->getCallingConv());
1598 Out << ");";
1599 nl(Out);
1600 if (F->hasSection()) {
1601 printCppName(F);
1602 Out << "->setSection(\"" << F->getSection() << "\");";
1603 nl(Out);
1604 }
1605 if (F->getAlignment()) {
1606 printCppName(F);
1607 Out << "->setAlignment(" << F->getAlignment() << ");";
1608 nl(Out);
1609 }
1610 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1611 printCppName(F);
1612 Out << "->setVisibility(";
1613 printVisibilityType(F->getVisibility());
1614 Out << ");";
1615 nl(Out);
1616 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001617 if (F->hasGC()) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001618 printCppName(F);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001619 Out << "->setGC(\"" << F->getGC() << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001620 nl(Out);
1621 }
1622 if (is_inline) {
1623 Out << "}";
1624 nl(Out);
1625 }
Devang Patel05988662008-09-25 21:00:45 +00001626 printAttributes(F->getAttributes(), getCppName(F));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001627 printCppName(F);
Devang Patel05988662008-09-25 21:00:45 +00001628 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001629 nl(Out);
1630 }
1631
1632 void CppWriter::printFunctionBody(const Function *F) {
1633 if (F->isDeclaration())
1634 return; // external functions have no bodies.
1635
1636 // Clear the DefinedValues and ForwardRefs maps because we can't have
1637 // cross-function forward refs
1638 ForwardRefs.clear();
1639 DefinedValues.clear();
1640
1641 // Create all the argument values
1642 if (!is_inline) {
1643 if (!F->arg_empty()) {
1644 Out << "Function::arg_iterator args = " << getCppName(F)
1645 << "->arg_begin();";
1646 nl(Out);
1647 }
1648 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1649 AI != AE; ++AI) {
1650 Out << "Value* " << getCppName(AI) << " = args++;";
1651 nl(Out);
1652 if (AI->hasName()) {
1653 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1654 nl(Out);
1655 }
1656 }
1657 }
1658
1659 // Create all the basic blocks
1660 nl(Out);
1661 for (Function::const_iterator BI = F->begin(), BE = F->end();
1662 BI != BE; ++BI) {
1663 std::string bbname(getCppName(BI));
1664 Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1665 if (BI->hasName())
1666 printEscapedString(BI->getName());
1667 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1668 nl(Out);
1669 }
1670
1671 // Output all of its basic blocks... for the function
1672 for (Function::const_iterator BI = F->begin(), BE = F->end();
1673 BI != BE; ++BI) {
1674 std::string bbname(getCppName(BI));
1675 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1676 nl(Out);
1677
1678 // Output all of the instructions in the basic block...
1679 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1680 I != E; ++I) {
1681 printInstruction(I,bbname);
1682 }
1683 }
1684
1685 // Loop over the ForwardRefs and resolve them now that all instructions
1686 // are generated.
1687 if (!ForwardRefs.empty()) {
1688 nl(Out) << "// Resolve Forward References";
1689 nl(Out);
1690 }
1691
1692 while (!ForwardRefs.empty()) {
1693 ForwardRefMap::iterator I = ForwardRefs.begin();
1694 Out << I->second << "->replaceAllUsesWith("
1695 << getCppName(I->first) << "); delete " << I->second << ";";
1696 nl(Out);
1697 ForwardRefs.erase(I);
1698 }
1699 }
1700
1701 void CppWriter::printInline(const std::string& fname,
1702 const std::string& func) {
1703 const Function* F = TheModule->getFunction(func);
1704 if (!F) {
1705 error(std::string("Function '") + func + "' not found in input module");
1706 return;
1707 }
1708 if (F->isDeclaration()) {
1709 error(std::string("Function '") + func + "' is external!");
1710 return;
1711 }
1712 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1713 << getCppName(F);
1714 unsigned arg_count = 1;
1715 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1716 AI != AE; ++AI) {
1717 Out << ", Value* arg_" << arg_count;
1718 }
1719 Out << ") {";
1720 nl(Out);
1721 is_inline = true;
1722 printFunctionUses(F);
1723 printFunctionBody(F);
1724 is_inline = false;
1725 Out << "return " << getCppName(F->begin()) << ";";
1726 nl(Out) << "}";
1727 nl(Out);
1728 }
1729
1730 void CppWriter::printModuleBody() {
1731 // Print out all the type definitions
1732 nl(Out) << "// Type Definitions"; nl(Out);
1733 printTypes(TheModule);
1734
1735 // Functions can call each other and global variables can reference them so
1736 // define all the functions first before emitting their function bodies.
1737 nl(Out) << "// Function Declarations"; nl(Out);
1738 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1739 I != E; ++I)
1740 printFunctionHead(I);
1741
1742 // Process the global variables declarations. We can't initialze them until
1743 // after the constants are printed so just print a header for each global
1744 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1745 for (Module::const_global_iterator I = TheModule->global_begin(),
1746 E = TheModule->global_end(); I != E; ++I) {
1747 printVariableHead(I);
1748 }
1749
1750 // Print out all the constants definitions. Constants don't recurse except
1751 // through GlobalValues. All GlobalValues have been declared at this point
1752 // so we can proceed to generate the constants.
1753 nl(Out) << "// Constant Definitions"; nl(Out);
1754 printConstants(TheModule);
1755
1756 // Process the global variables definitions now that all the constants have
1757 // been emitted. These definitions just couple the gvars with their constant
1758 // initializers.
1759 nl(Out) << "// Global Variable Definitions"; nl(Out);
1760 for (Module::const_global_iterator I = TheModule->global_begin(),
1761 E = TheModule->global_end(); I != E; ++I) {
1762 printVariableBody(I);
1763 }
1764
1765 // Finally, we can safely put out all of the function bodies.
1766 nl(Out) << "// Function Definitions"; nl(Out);
1767 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1768 I != E; ++I) {
1769 if (!I->isDeclaration()) {
1770 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1771 << ")";
1772 nl(Out) << "{";
1773 nl(Out,1);
1774 printFunctionBody(I);
1775 nl(Out,-1) << "}";
1776 nl(Out);
1777 }
1778 }
1779 }
1780
1781 void CppWriter::printProgram(const std::string& fname,
1782 const std::string& mName) {
1783 Out << "#include <llvm/Module.h>\n";
1784 Out << "#include <llvm/DerivedTypes.h>\n";
1785 Out << "#include <llvm/Constants.h>\n";
1786 Out << "#include <llvm/GlobalVariable.h>\n";
1787 Out << "#include <llvm/Function.h>\n";
1788 Out << "#include <llvm/CallingConv.h>\n";
1789 Out << "#include <llvm/BasicBlock.h>\n";
1790 Out << "#include <llvm/Instructions.h>\n";
1791 Out << "#include <llvm/InlineAsm.h>\n";
1792 Out << "#include <llvm/Support/MathExtras.h>\n";
Dan Gohmanf9231292008-12-08 07:07:24 +00001793 Out << "#include <llvm/Support/raw_ostream.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001794 Out << "#include <llvm/Pass.h>\n";
1795 Out << "#include <llvm/PassManager.h>\n";
Nicolas Geoffray9474ede2008-05-14 07:52:03 +00001796 Out << "#include <llvm/ADT/SmallVector.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001797 Out << "#include <llvm/Analysis/Verifier.h>\n";
1798 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1799 Out << "#include <algorithm>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001800 Out << "using namespace llvm;\n\n";
1801 Out << "Module* " << fname << "();\n\n";
1802 Out << "int main(int argc, char**argv) {\n";
1803 Out << " Module* Mod = " << fname << "();\n";
1804 Out << " verifyModule(*Mod, PrintMessageAction);\n";
Dan Gohmanf9231292008-12-08 07:07:24 +00001805 Out << " errs().flush();\n";
1806 Out << " outs().flush();\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001807 Out << " PassManager PM;\n";
Dan Gohmanf9231292008-12-08 07:07:24 +00001808 Out << " PM.add(createPrintModulePass(&outs()));\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001809 Out << " PM.run(*Mod);\n";
1810 Out << " return 0;\n";
1811 Out << "}\n\n";
1812 printModule(fname,mName);
1813 }
1814
1815 void CppWriter::printModule(const std::string& fname,
1816 const std::string& mName) {
1817 nl(Out) << "Module* " << fname << "() {";
1818 nl(Out,1) << "// Module Construction";
1819 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1820 if (!TheModule->getTargetTriple().empty()) {
1821 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1822 }
1823 if (!TheModule->getTargetTriple().empty()) {
1824 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1825 << "\");";
1826 }
1827
1828 if (!TheModule->getModuleInlineAsm().empty()) {
1829 nl(Out) << "mod->setModuleInlineAsm(\"";
1830 printEscapedString(TheModule->getModuleInlineAsm());
1831 Out << "\");";
1832 }
1833 nl(Out);
1834
1835 // Loop over the dependent libraries and emit them.
1836 Module::lib_iterator LI = TheModule->lib_begin();
1837 Module::lib_iterator LE = TheModule->lib_end();
1838 while (LI != LE) {
1839 Out << "mod->addLibrary(\"" << *LI << "\");";
1840 nl(Out);
1841 ++LI;
1842 }
1843 printModuleBody();
1844 nl(Out) << "return mod;";
1845 nl(Out,-1) << "}";
1846 nl(Out);
1847 }
1848
1849 void CppWriter::printContents(const std::string& fname,
1850 const std::string& mName) {
1851 Out << "\nModule* " << fname << "(Module *mod) {\n";
1852 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1853 printModuleBody();
1854 Out << "\nreturn mod;\n";
1855 Out << "\n}\n";
1856 }
1857
1858 void CppWriter::printFunction(const std::string& fname,
1859 const std::string& funcName) {
1860 const Function* F = TheModule->getFunction(funcName);
1861 if (!F) {
1862 error(std::string("Function '") + funcName + "' not found in input module");
1863 return;
1864 }
1865 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1866 printFunctionUses(F);
1867 printFunctionHead(F);
1868 printFunctionBody(F);
1869 Out << "return " << getCppName(F) << ";\n";
1870 Out << "}\n";
1871 }
1872
1873 void CppWriter::printFunctions() {
1874 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1875 Module::const_iterator I = funcs.begin();
1876 Module::const_iterator IE = funcs.end();
1877
1878 for (; I != IE; ++I) {
1879 const Function &func = *I;
1880 if (!func.isDeclaration()) {
1881 std::string name("define_");
1882 name += func.getName();
1883 printFunction(name, func.getName());
1884 }
1885 }
1886 }
1887
1888 void CppWriter::printVariable(const std::string& fname,
1889 const std::string& varName) {
1890 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1891
1892 if (!GV) {
1893 error(std::string("Variable '") + varName + "' not found in input module");
1894 return;
1895 }
1896 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1897 printVariableUses(GV);
1898 printVariableHead(GV);
1899 printVariableBody(GV);
1900 Out << "return " << getCppName(GV) << ";\n";
1901 Out << "}\n";
1902 }
1903
1904 void CppWriter::printType(const std::string& fname,
1905 const std::string& typeName) {
1906 const Type* Ty = TheModule->getTypeByName(typeName);
1907 if (!Ty) {
1908 error(std::string("Type '") + typeName + "' not found in input module");
1909 return;
1910 }
1911 Out << "\nType* " << fname << "(Module *mod) {\n";
1912 printType(Ty);
1913 Out << "return " << getCppName(Ty) << ";\n";
1914 Out << "}\n";
1915 }
1916
1917 bool CppWriter::runOnModule(Module &M) {
1918 TheModule = &M;
1919
1920 // Emit a header
1921 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1922
1923 // Get the name of the function we're supposed to generate
1924 std::string fname = FuncName.getValue();
1925
1926 // Get the name of the thing we are to generate
1927 std::string tgtname = NameToGenerate.getValue();
1928 if (GenerationType == GenModule ||
1929 GenerationType == GenContents ||
1930 GenerationType == GenProgram ||
1931 GenerationType == GenFunctions) {
1932 if (tgtname == "!bad!") {
1933 if (M.getModuleIdentifier() == "-")
1934 tgtname = "<stdin>";
1935 else
1936 tgtname = M.getModuleIdentifier();
1937 }
1938 } else if (tgtname == "!bad!")
1939 error("You must use the -for option with -gen-{function,variable,type}");
1940
1941 switch (WhatToGenerate(GenerationType)) {
1942 case GenProgram:
1943 if (fname.empty())
1944 fname = "makeLLVMModule";
1945 printProgram(fname,tgtname);
1946 break;
1947 case GenModule:
1948 if (fname.empty())
1949 fname = "makeLLVMModule";
1950 printModule(fname,tgtname);
1951 break;
1952 case GenContents:
1953 if (fname.empty())
1954 fname = "makeLLVMModuleContents";
1955 printContents(fname,tgtname);
1956 break;
1957 case GenFunction:
1958 if (fname.empty())
1959 fname = "makeLLVMFunction";
1960 printFunction(fname,tgtname);
1961 break;
1962 case GenFunctions:
1963 printFunctions();
1964 break;
1965 case GenInline:
1966 if (fname.empty())
1967 fname = "makeLLVMInline";
1968 printInline(fname,tgtname);
1969 break;
1970 case GenVariable:
1971 if (fname.empty())
1972 fname = "makeLLVMVariable";
1973 printVariable(fname,tgtname);
1974 break;
1975 case GenType:
1976 if (fname.empty())
1977 fname = "makeLLVMType";
1978 printType(fname,tgtname);
1979 break;
1980 default:
1981 error("Invalid generation option");
1982 }
1983
1984 return false;
1985 }
1986}
1987
1988char CppWriter::ID = 0;
1989
1990//===----------------------------------------------------------------------===//
1991// External Interface declaration
1992//===----------------------------------------------------------------------===//
1993
1994bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
Owen Andersoncb371882008-08-21 00:14:44 +00001995 raw_ostream &o,
Anton Korobeynikov50276522008-04-23 22:29:24 +00001996 CodeGenFileType FileType,
1997 bool Fast) {
1998 if (FileType != TargetMachine::AssemblyFile) return true;
1999 PM.add(new CppWriter(o));
2000 return false;
2001}