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