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