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