blob: 7c5d09ec1b0e99f50b44a74d347b061df32a97b5 [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"
Torok Edwin30464702009-07-08 20:55:50 +000031#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000032#include "llvm/Support/FormattedStream.h"
Bill Wendling1a53ead2008-07-27 23:18:30 +000033#include "llvm/Support/Streams.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
Dan Gohman844731a2008-05-13 00:00:25 +000075// Register the target.
Daniel Dunbar51b198a2009-07-15 20:24:03 +000076static RegisterTarget<CPPTargetMachine> X(TheCppBackendTarget, "cpp", "C++ backend");
Anton Korobeynikov50276522008-04-23 22:29:24 +000077
Bob Wilsona96751f2009-06-23 23:59:40 +000078// Force static initialization.
79extern "C" void LLVMInitializeCppBackendTarget() { }
Douglas Gregor1555a232009-06-16 20:12:29 +000080
Dan Gohman844731a2008-05-13 00:00:25 +000081namespace {
Anton Korobeynikov50276522008-04-23 22:29:24 +000082 typedef std::vector<const Type*> TypeList;
83 typedef std::map<const Type*,std::string> TypeMap;
84 typedef std::map<const Value*,std::string> ValueMap;
85 typedef std::set<std::string> NameSet;
86 typedef std::set<const Type*> TypeSet;
87 typedef std::set<const Value*> ValueSet;
88 typedef std::map<const Value*,std::string> ForwardRefMap;
89
90 /// CppWriter - This class is the main chunk of code that converts an LLVM
91 /// module to a C++ translation unit.
92 class CppWriter : public ModulePass {
David Greene71847812009-07-14 20:18:05 +000093 formatted_raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +000094 const Module *TheModule;
95 uint64_t uniqueNum;
96 TypeMap TypeNames;
97 ValueMap ValueNames;
98 TypeMap UnresolvedTypes;
99 TypeList TypeStack;
100 NameSet UsedNames;
101 TypeSet DefinedTypes;
102 ValueSet DefinedValues;
103 ForwardRefMap ForwardRefs;
104 bool is_inline;
105
106 public:
107 static char ID;
David Greene71847812009-07-14 20:18:05 +0000108 explicit CppWriter(formatted_raw_ostream &o) :
Dan Gohmanae73dc12008-09-04 17:05:41 +0000109 ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000110
111 virtual const char *getPassName() const { return "C++ backend"; }
112
113 bool runOnModule(Module &M);
114
Anton Korobeynikov50276522008-04-23 22:29:24 +0000115 void printProgram(const std::string& fname, const std::string& modName );
116 void printModule(const std::string& fname, const std::string& modName );
117 void printContents(const std::string& fname, const std::string& modName );
118 void printFunction(const std::string& fname, const std::string& funcName );
119 void printFunctions();
120 void printInline(const std::string& fname, const std::string& funcName );
121 void printVariable(const std::string& fname, const std::string& varName );
122 void printType(const std::string& fname, const std::string& typeName );
123
124 void error(const std::string& msg);
125
126 private:
127 void printLinkageType(GlobalValue::LinkageTypes LT);
128 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
129 void printCallingConv(unsigned cc);
130 void printEscapedString(const std::string& str);
131 void printCFP(const ConstantFP* CFP);
132
133 std::string getCppName(const Type* val);
134 inline void printCppName(const Type* val);
135
136 std::string getCppName(const Value* val);
137 inline void printCppName(const Value* val);
138
Devang Patel05988662008-09-25 21:00:45 +0000139 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000140 bool printTypeInternal(const Type* Ty);
141 inline void printType(const Type* Ty);
142 void printTypes(const Module* M);
143
144 void printConstant(const Constant *CPV);
145 void printConstants(const Module* M);
146
147 void printVariableUses(const GlobalVariable *GV);
148 void printVariableHead(const GlobalVariable *GV);
149 void printVariableBody(const GlobalVariable *GV);
150
151 void printFunctionUses(const Function *F);
152 void printFunctionHead(const Function *F);
153 void printFunctionBody(const Function *F);
154 void printInstruction(const Instruction *I, const std::string& bbname);
155 std::string getOpName(Value*);
156
157 void printModuleBody();
158 };
159
160 static unsigned indent_level = 0;
David Greene71847812009-07-14 20:18:05 +0000161 inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000162 Out << "\n";
163 if (delta >= 0 || indent_level >= unsigned(-delta))
164 indent_level += delta;
165 for (unsigned i = 0; i < indent_level; ++i)
166 Out << " ";
167 return Out;
168 }
169
170 inline void in() { indent_level++; }
171 inline void out() { if (indent_level >0) indent_level--; }
172
173 inline void
174 sanitize(std::string& str) {
175 for (size_t i = 0; i < str.length(); ++i)
176 if (!isalnum(str[i]) && str[i] != '_')
177 str[i] = '_';
178 }
179
180 inline std::string
181 getTypePrefix(const Type* Ty ) {
182 switch (Ty->getTypeID()) {
183 case Type::VoidTyID: return "void_";
184 case Type::IntegerTyID:
185 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
186 "_";
187 case Type::FloatTyID: return "float_";
188 case Type::DoubleTyID: return "double_";
189 case Type::LabelTyID: return "label_";
190 case Type::FunctionTyID: return "func_";
191 case Type::StructTyID: return "struct_";
192 case Type::ArrayTyID: return "array_";
193 case Type::PointerTyID: return "ptr_";
194 case Type::VectorTyID: return "packed_";
195 case Type::OpaqueTyID: return "opaque_";
196 default: return "other_";
197 }
198 return "unknown_";
199 }
200
201 // Looks up the type in the symbol table and returns a pointer to its name or
202 // a null pointer if it wasn't found. Note that this isn't the same as the
203 // Mode::getTypeName function which will return an empty string, not a null
204 // pointer if the name is not found.
205 inline const std::string*
206 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
207 TypeSymbolTable::const_iterator TI = ST.begin();
208 TypeSymbolTable::const_iterator TE = ST.end();
209 for (;TI != TE; ++TI)
210 if (TI->second == Ty)
211 return &(TI->first);
212 return 0;
213 }
214
215 void CppWriter::error(const std::string& msg) {
Torok Edwin30464702009-07-08 20:55:50 +0000216 llvm_report_error(msg);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000217 }
218
219 // printCFP - Print a floating point constant .. very carefully :)
220 // This makes sure that conversion to/from floating yields the same binary
221 // result so that we don't lose precision.
222 void CppWriter::printCFP(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000223 bool ignored;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000224 APFloat APF = APFloat(CFP->getValueAPF()); // copy
225 if (CFP->getType() == Type::FloatTy)
Dale Johannesen23a98552008-10-09 23:00:39 +0000226 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000227 Out << "ConstantFP::get(";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000228 Out << "APFloat(";
229#if HAVE_PRINTF_A
230 char Buffer[100];
231 sprintf(Buffer, "%A", APF.convertToDouble());
232 if ((!strncmp(Buffer, "0x", 2) ||
233 !strncmp(Buffer, "-0x", 3) ||
234 !strncmp(Buffer, "+0x", 3)) &&
235 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
236 if (CFP->getType() == Type::DoubleTy)
237 Out << "BitsToDouble(" << Buffer << ")";
238 else
239 Out << "BitsToFloat((float)" << Buffer << ")";
240 Out << ")";
241 } else {
242#endif
243 std::string StrVal = ftostr(CFP->getValueAPF());
244
245 while (StrVal[0] == ' ')
246 StrVal.erase(StrVal.begin());
247
248 // Check to make sure that the stringized number is not some string like
249 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
250 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
251 ((StrVal[0] == '-' || StrVal[0] == '+') &&
252 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
253 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
254 if (CFP->getType() == Type::DoubleTy)
255 Out << StrVal;
256 else
257 Out << StrVal << "f";
258 } else if (CFP->getType() == Type::DoubleTy)
Owen Andersoncb371882008-08-21 00:14:44 +0000259 Out << "BitsToDouble(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000260 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000261 << "ULL) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000262 else
Owen Andersoncb371882008-08-21 00:14:44 +0000263 Out << "BitsToFloat(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000264 << utohexstr((uint32_t)CFP->getValueAPF().
265 bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000266 << "U) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000267 Out << ")";
268#if HAVE_PRINTF_A
269 }
270#endif
271 Out << ")";
272 }
273
274 void CppWriter::printCallingConv(unsigned cc){
275 // Print the calling convention.
276 switch (cc) {
277 case CallingConv::C: Out << "CallingConv::C"; break;
278 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
279 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
280 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
281 default: Out << cc; break;
282 }
283 }
284
285 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
286 switch (LT) {
287 case GlobalValue::InternalLinkage:
288 Out << "GlobalValue::InternalLinkage"; break;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000289 case GlobalValue::PrivateLinkage:
290 Out << "GlobalValue::PrivateLinkage"; break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000291 case GlobalValue::LinkerPrivateLinkage:
292 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000293 case GlobalValue::AvailableExternallyLinkage:
294 Out << "GlobalValue::AvailableExternallyLinkage "; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000295 case GlobalValue::LinkOnceAnyLinkage:
296 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
297 case GlobalValue::LinkOnceODRLinkage:
298 Out << "GlobalValue::LinkOnceODRLinkage "; break;
299 case GlobalValue::WeakAnyLinkage:
300 Out << "GlobalValue::WeakAnyLinkage"; break;
301 case GlobalValue::WeakODRLinkage:
302 Out << "GlobalValue::WeakODRLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000303 case GlobalValue::AppendingLinkage:
304 Out << "GlobalValue::AppendingLinkage"; break;
305 case GlobalValue::ExternalLinkage:
306 Out << "GlobalValue::ExternalLinkage"; break;
307 case GlobalValue::DLLImportLinkage:
308 Out << "GlobalValue::DLLImportLinkage"; break;
309 case GlobalValue::DLLExportLinkage:
310 Out << "GlobalValue::DLLExportLinkage"; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000311 case GlobalValue::ExternalWeakLinkage:
312 Out << "GlobalValue::ExternalWeakLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000313 case GlobalValue::GhostLinkage:
314 Out << "GlobalValue::GhostLinkage"; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000315 case GlobalValue::CommonLinkage:
316 Out << "GlobalValue::CommonLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000317 }
318 }
319
320 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
321 switch (VisType) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000322 default: llvm_unreachable("Unknown GVar visibility");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000323 case GlobalValue::DefaultVisibility:
324 Out << "GlobalValue::DefaultVisibility";
325 break;
326 case GlobalValue::HiddenVisibility:
327 Out << "GlobalValue::HiddenVisibility";
328 break;
329 case GlobalValue::ProtectedVisibility:
330 Out << "GlobalValue::ProtectedVisibility";
331 break;
332 }
333 }
334
335 // printEscapedString - Print each character of the specified string, escaping
336 // it if it is not printable or if it is an escape char.
337 void CppWriter::printEscapedString(const std::string &Str) {
338 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
339 unsigned char C = Str[i];
340 if (isprint(C) && C != '"' && C != '\\') {
341 Out << C;
342 } else {
343 Out << "\\x"
344 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
345 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
346 }
347 }
348 }
349
350 std::string CppWriter::getCppName(const Type* Ty) {
351 // First, handle the primitive types .. easy
352 if (Ty->isPrimitiveType() || Ty->isInteger()) {
353 switch (Ty->getTypeID()) {
354 case Type::VoidTyID: return "Type::VoidTy";
355 case Type::IntegerTyID: {
356 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
357 return "IntegerType::get(" + utostr(BitWidth) + ")";
358 }
Chris Lattnerc650f1f2009-05-01 23:54:26 +0000359 case Type::X86_FP80TyID: return "Type::X86_FP80Ty";
360 case Type::FloatTyID: return "Type::FloatTy";
361 case Type::DoubleTyID: return "Type::DoubleTy";
362 case Type::LabelTyID: return "Type::LabelTy";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000363 default:
364 error("Invalid primitive type");
365 break;
366 }
367 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
368 }
369
370 // Now, see if we've seen the type before and return that
371 TypeMap::iterator I = TypeNames.find(Ty);
372 if (I != TypeNames.end())
373 return I->second;
374
375 // Okay, let's build a new name for this type. Start with a prefix
376 const char* prefix = 0;
377 switch (Ty->getTypeID()) {
378 case Type::FunctionTyID: prefix = "FuncTy_"; break;
379 case Type::StructTyID: prefix = "StructTy_"; break;
380 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
381 case Type::PointerTyID: prefix = "PointerTy_"; break;
382 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
383 case Type::VectorTyID: prefix = "VectorTy_"; break;
384 default: prefix = "OtherTy_"; break; // prevent breakage
385 }
386
387 // See if the type has a name in the symboltable and build accordingly
388 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
389 std::string name;
390 if (tName)
391 name = std::string(prefix) + *tName;
392 else
393 name = std::string(prefix) + utostr(uniqueNum++);
394 sanitize(name);
395
396 // Save the name
397 return TypeNames[Ty] = name;
398 }
399
400 void CppWriter::printCppName(const Type* Ty) {
401 printEscapedString(getCppName(Ty));
402 }
403
404 std::string CppWriter::getCppName(const Value* val) {
405 std::string name;
406 ValueMap::iterator I = ValueNames.find(val);
407 if (I != ValueNames.end() && I->first == val)
408 return I->second;
409
410 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
411 name = std::string("gvar_") +
412 getTypePrefix(GV->getType()->getElementType());
413 } else if (isa<Function>(val)) {
414 name = std::string("func_");
415 } else if (const Constant* C = dyn_cast<Constant>(val)) {
416 name = std::string("const_") + getTypePrefix(C->getType());
417 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
418 if (is_inline) {
419 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
420 Function::const_arg_iterator(Arg)) + 1;
421 name = std::string("arg_") + utostr(argNum);
422 NameSet::iterator NI = UsedNames.find(name);
423 if (NI != UsedNames.end())
424 name += std::string("_") + utostr(uniqueNum++);
425 UsedNames.insert(name);
426 return ValueNames[val] = name;
427 } else {
428 name = getTypePrefix(val->getType());
429 }
430 } else {
431 name = getTypePrefix(val->getType());
432 }
Daniel Dunbar8f603022009-07-22 21:10:12 +0000433 if (val->hasName())
434 name += val->getName();
435 else
436 name += utostr(uniqueNum++);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000437 sanitize(name);
438 NameSet::iterator NI = UsedNames.find(name);
439 if (NI != UsedNames.end())
440 name += std::string("_") + utostr(uniqueNum++);
441 UsedNames.insert(name);
442 return ValueNames[val] = name;
443 }
444
445 void CppWriter::printCppName(const Value* val) {
446 printEscapedString(getCppName(val));
447 }
448
Devang Patel05988662008-09-25 21:00:45 +0000449 void CppWriter::printAttributes(const AttrListPtr &PAL,
Anton Korobeynikov50276522008-04-23 22:29:24 +0000450 const std::string &name) {
Devang Patel05988662008-09-25 21:00:45 +0000451 Out << "AttrListPtr " << name << "_PAL;";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000452 nl(Out);
453 if (!PAL.isEmpty()) {
454 Out << '{'; in(); nl(Out);
Devang Patel05988662008-09-25 21:00:45 +0000455 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
456 Out << "AttributeWithIndex PAWI;"; nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000457 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000458 unsigned index = PAL.getSlot(i).Index;
Devang Pateleaf42ab2008-09-23 23:03:40 +0000459 Attributes attrs = PAL.getSlot(i).Attrs;
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000460 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
Chris Lattneracca9552009-01-13 07:22:22 +0000461#define HANDLE_ATTR(X) \
462 if (attrs & Attribute::X) \
463 Out << " | Attribute::" #X; \
464 attrs &= ~Attribute::X;
465
466 HANDLE_ATTR(SExt);
467 HANDLE_ATTR(ZExt);
Chris Lattneracca9552009-01-13 07:22:22 +0000468 HANDLE_ATTR(NoReturn);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000469 HANDLE_ATTR(InReg);
470 HANDLE_ATTR(StructRet);
Chris Lattneracca9552009-01-13 07:22:22 +0000471 HANDLE_ATTR(NoUnwind);
Chris Lattneracca9552009-01-13 07:22:22 +0000472 HANDLE_ATTR(NoAlias);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000473 HANDLE_ATTR(ByVal);
Chris Lattneracca9552009-01-13 07:22:22 +0000474 HANDLE_ATTR(Nest);
475 HANDLE_ATTR(ReadNone);
476 HANDLE_ATTR(ReadOnly);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000477 HANDLE_ATTR(NoInline);
478 HANDLE_ATTR(AlwaysInline);
479 HANDLE_ATTR(OptimizeForSize);
480 HANDLE_ATTR(StackProtect);
481 HANDLE_ATTR(StackProtectReq);
Chris Lattneracca9552009-01-13 07:22:22 +0000482 HANDLE_ATTR(NoCapture);
483#undef HANDLE_ATTR
484 assert(attrs == 0 && "Unhandled attribute!");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000485 Out << ";";
486 nl(Out);
487 Out << "Attrs.push_back(PAWI);";
488 nl(Out);
489 }
Devang Patel05988662008-09-25 21:00:45 +0000490 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000491 nl(Out);
492 out(); nl(Out);
493 Out << '}'; nl(Out);
494 }
495 }
496
497 bool CppWriter::printTypeInternal(const Type* Ty) {
498 // We don't print definitions for primitive types
499 if (Ty->isPrimitiveType() || Ty->isInteger())
500 return false;
501
502 // If we already defined this type, we don't need to define it again.
503 if (DefinedTypes.find(Ty) != DefinedTypes.end())
504 return false;
505
506 // Everything below needs the name for the type so get it now.
507 std::string typeName(getCppName(Ty));
508
509 // Search the type stack for recursion. If we find it, then generate this
510 // as an OpaqueType, but make sure not to do this multiple times because
511 // the type could appear in multiple places on the stack. Once the opaque
512 // definition is issued, it must not be re-issued. Consequently we have to
513 // check the UnresolvedTypes list as well.
514 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
515 Ty);
516 if (TI != TypeStack.end()) {
517 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
518 if (I == UnresolvedTypes.end()) {
519 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
520 nl(Out);
521 UnresolvedTypes[Ty] = typeName;
522 }
523 return true;
524 }
525
526 // We're going to print a derived type which, by definition, contains other
527 // types. So, push this one we're printing onto the type stack to assist with
528 // recursive definitions.
529 TypeStack.push_back(Ty);
530
531 // Print the type definition
532 switch (Ty->getTypeID()) {
533 case Type::FunctionTyID: {
534 const FunctionType* FT = cast<FunctionType>(Ty);
535 Out << "std::vector<const Type*>" << typeName << "_args;";
536 nl(Out);
537 FunctionType::param_iterator PI = FT->param_begin();
538 FunctionType::param_iterator PE = FT->param_end();
539 for (; PI != PE; ++PI) {
540 const Type* argTy = static_cast<const Type*>(*PI);
541 bool isForward = printTypeInternal(argTy);
542 std::string argName(getCppName(argTy));
543 Out << typeName << "_args.push_back(" << argName;
544 if (isForward)
545 Out << "_fwd";
546 Out << ");";
547 nl(Out);
548 }
549 bool isForward = printTypeInternal(FT->getReturnType());
550 std::string retTypeName(getCppName(FT->getReturnType()));
551 Out << "FunctionType* " << typeName << " = FunctionType::get(";
552 in(); nl(Out) << "/*Result=*/" << retTypeName;
553 if (isForward)
554 Out << "_fwd";
555 Out << ",";
556 nl(Out) << "/*Params=*/" << typeName << "_args,";
557 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
558 out();
559 nl(Out);
560 break;
561 }
562 case Type::StructTyID: {
563 const StructType* ST = cast<StructType>(Ty);
564 Out << "std::vector<const Type*>" << typeName << "_fields;";
565 nl(Out);
566 StructType::element_iterator EI = ST->element_begin();
567 StructType::element_iterator EE = ST->element_end();
568 for (; EI != EE; ++EI) {
569 const Type* fieldTy = static_cast<const Type*>(*EI);
570 bool isForward = printTypeInternal(fieldTy);
571 std::string fieldName(getCppName(fieldTy));
572 Out << typeName << "_fields.push_back(" << fieldName;
573 if (isForward)
574 Out << "_fwd";
575 Out << ");";
576 nl(Out);
577 }
578 Out << "StructType* " << typeName << " = StructType::get("
579 << 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";
Dan Gohmanf9231292008-12-08 07:07:24 +00001820 Out << " outs().flush();\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001821 Out << " PassManager PM;\n";
Dan Gohmanf9231292008-12-08 07:07:24 +00001822 Out << " PM.add(createPrintModulePass(&outs()));\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001823 Out << " PM.run(*Mod);\n";
1824 Out << " return 0;\n";
1825 Out << "}\n\n";
1826 printModule(fname,mName);
1827 }
1828
1829 void CppWriter::printModule(const std::string& fname,
1830 const std::string& mName) {
1831 nl(Out) << "Module* " << fname << "() {";
1832 nl(Out,1) << "// Module Construction";
Nick Lewyckyb8b73472009-06-26 04:33:37 +00001833 nl(Out) << "Module* mod = new Module(\"";
1834 printEscapedString(mName);
1835 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001836 if (!TheModule->getTargetTriple().empty()) {
1837 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1838 }
1839 if (!TheModule->getTargetTriple().empty()) {
1840 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1841 << "\");";
1842 }
1843
1844 if (!TheModule->getModuleInlineAsm().empty()) {
1845 nl(Out) << "mod->setModuleInlineAsm(\"";
1846 printEscapedString(TheModule->getModuleInlineAsm());
1847 Out << "\");";
1848 }
1849 nl(Out);
1850
1851 // Loop over the dependent libraries and emit them.
1852 Module::lib_iterator LI = TheModule->lib_begin();
1853 Module::lib_iterator LE = TheModule->lib_end();
1854 while (LI != LE) {
1855 Out << "mod->addLibrary(\"" << *LI << "\");";
1856 nl(Out);
1857 ++LI;
1858 }
1859 printModuleBody();
1860 nl(Out) << "return mod;";
1861 nl(Out,-1) << "}";
1862 nl(Out);
1863 }
1864
1865 void CppWriter::printContents(const std::string& fname,
1866 const std::string& mName) {
1867 Out << "\nModule* " << fname << "(Module *mod) {\n";
Nick Lewyckyb8b73472009-06-26 04:33:37 +00001868 Out << "\nmod->setModuleIdentifier(\"";
1869 printEscapedString(mName);
1870 Out << "\");\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001871 printModuleBody();
1872 Out << "\nreturn mod;\n";
1873 Out << "\n}\n";
1874 }
1875
1876 void CppWriter::printFunction(const std::string& fname,
1877 const std::string& funcName) {
1878 const Function* F = TheModule->getFunction(funcName);
1879 if (!F) {
1880 error(std::string("Function '") + funcName + "' not found in input module");
1881 return;
1882 }
1883 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1884 printFunctionUses(F);
1885 printFunctionHead(F);
1886 printFunctionBody(F);
1887 Out << "return " << getCppName(F) << ";\n";
1888 Out << "}\n";
1889 }
1890
1891 void CppWriter::printFunctions() {
1892 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1893 Module::const_iterator I = funcs.begin();
1894 Module::const_iterator IE = funcs.end();
1895
1896 for (; I != IE; ++I) {
1897 const Function &func = *I;
1898 if (!func.isDeclaration()) {
1899 std::string name("define_");
1900 name += func.getName();
1901 printFunction(name, func.getName());
1902 }
1903 }
1904 }
1905
1906 void CppWriter::printVariable(const std::string& fname,
1907 const std::string& varName) {
1908 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1909
1910 if (!GV) {
1911 error(std::string("Variable '") + varName + "' not found in input module");
1912 return;
1913 }
1914 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1915 printVariableUses(GV);
1916 printVariableHead(GV);
1917 printVariableBody(GV);
1918 Out << "return " << getCppName(GV) << ";\n";
1919 Out << "}\n";
1920 }
1921
1922 void CppWriter::printType(const std::string& fname,
1923 const std::string& typeName) {
1924 const Type* Ty = TheModule->getTypeByName(typeName);
1925 if (!Ty) {
1926 error(std::string("Type '") + typeName + "' not found in input module");
1927 return;
1928 }
1929 Out << "\nType* " << fname << "(Module *mod) {\n";
1930 printType(Ty);
1931 Out << "return " << getCppName(Ty) << ";\n";
1932 Out << "}\n";
1933 }
1934
1935 bool CppWriter::runOnModule(Module &M) {
1936 TheModule = &M;
1937
1938 // Emit a header
1939 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1940
1941 // Get the name of the function we're supposed to generate
1942 std::string fname = FuncName.getValue();
1943
1944 // Get the name of the thing we are to generate
1945 std::string tgtname = NameToGenerate.getValue();
1946 if (GenerationType == GenModule ||
1947 GenerationType == GenContents ||
1948 GenerationType == GenProgram ||
1949 GenerationType == GenFunctions) {
1950 if (tgtname == "!bad!") {
1951 if (M.getModuleIdentifier() == "-")
1952 tgtname = "<stdin>";
1953 else
1954 tgtname = M.getModuleIdentifier();
1955 }
1956 } else if (tgtname == "!bad!")
1957 error("You must use the -for option with -gen-{function,variable,type}");
1958
1959 switch (WhatToGenerate(GenerationType)) {
1960 case GenProgram:
1961 if (fname.empty())
1962 fname = "makeLLVMModule";
1963 printProgram(fname,tgtname);
1964 break;
1965 case GenModule:
1966 if (fname.empty())
1967 fname = "makeLLVMModule";
1968 printModule(fname,tgtname);
1969 break;
1970 case GenContents:
1971 if (fname.empty())
1972 fname = "makeLLVMModuleContents";
1973 printContents(fname,tgtname);
1974 break;
1975 case GenFunction:
1976 if (fname.empty())
1977 fname = "makeLLVMFunction";
1978 printFunction(fname,tgtname);
1979 break;
1980 case GenFunctions:
1981 printFunctions();
1982 break;
1983 case GenInline:
1984 if (fname.empty())
1985 fname = "makeLLVMInline";
1986 printInline(fname,tgtname);
1987 break;
1988 case GenVariable:
1989 if (fname.empty())
1990 fname = "makeLLVMVariable";
1991 printVariable(fname,tgtname);
1992 break;
1993 case GenType:
1994 if (fname.empty())
1995 fname = "makeLLVMType";
1996 printType(fname,tgtname);
1997 break;
1998 default:
1999 error("Invalid generation option");
2000 }
2001
2002 return false;
2003 }
2004}
2005
2006char CppWriter::ID = 0;
2007
2008//===----------------------------------------------------------------------===//
2009// External Interface declaration
2010//===----------------------------------------------------------------------===//
2011
2012bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
David Greene71847812009-07-14 20:18:05 +00002013 formatted_raw_ostream &o,
Anton Korobeynikov50276522008-04-23 22:29:24 +00002014 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00002015 CodeGenOpt::Level OptLevel) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00002016 if (FileType != TargetMachine::AssemblyFile) return true;
2017 PM.add(new CppWriter(o));
2018 return false;
2019}