blob: b1934370ce2667a5fe5cfb10ed8716945e0f2d17 [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"
Evan Cheng59ee62d2011-07-11 03:57:24 +000025#include "llvm/MC/MCInstrInfo.h"
Evan Chengffc0e732011-07-09 05:47:46 +000026#include "llvm/MC/MCSubtargetInfo.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/Support/CommandLine.h"
Torok Edwin30464702009-07-08 20:55:50 +000029#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000030#include "llvm/Support/FormattedStream.h"
Daniel Dunbar0c795d62009-07-25 06:49:55 +000031#include "llvm/Target/TargetRegistry.h"
Chris Lattner23132b12009-08-24 03:52:50 +000032#include "llvm/ADT/StringExtras.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>
Chris Lattner1afcace2011-07-09 17:41:24 +000036#include <map>
Anton Korobeynikov50276522008-04-23 22:29:24 +000037using 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
Daniel Dunbar0c795d62009-07-25 06:49:55 +000074extern "C" void LLVMInitializeCppBackendTarget() {
75 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000076 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000077}
Douglas Gregor1555a232009-06-16 20:12:29 +000078
Evan Cheng59ee62d2011-07-11 03:57:24 +000079extern "C" void LLVMInitializeCppBackendMCInstrInfo() {
80 RegisterMCInstrInfo<MCInstrInfo> X(TheCppBackendTarget);
81}
82
Evan Chengffc0e732011-07-09 05:47:46 +000083extern "C" void LLVMInitializeCppBackendMCSubtargetInfo() {
84 RegisterMCSubtargetInfo<MCSubtargetInfo> X(TheCppBackendTarget);
85}
86
Dan Gohman844731a2008-05-13 00:00:25 +000087namespace {
Anton Korobeynikov50276522008-04-23 22:29:24 +000088 typedef std::vector<const Type*> TypeList;
89 typedef std::map<const Type*,std::string> TypeMap;
90 typedef std::map<const Value*,std::string> ValueMap;
91 typedef std::set<std::string> NameSet;
92 typedef std::set<const Type*> TypeSet;
93 typedef std::set<const Value*> ValueSet;
94 typedef std::map<const Value*,std::string> ForwardRefMap;
95
96 /// CppWriter - This class is the main chunk of code that converts an LLVM
97 /// module to a C++ translation unit.
98 class CppWriter : public ModulePass {
David Greene71847812009-07-14 20:18:05 +000099 formatted_raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000100 const Module *TheModule;
101 uint64_t uniqueNum;
102 TypeMap TypeNames;
103 ValueMap ValueNames;
104 TypeMap UnresolvedTypes;
105 TypeList TypeStack;
106 NameSet UsedNames;
107 TypeSet DefinedTypes;
108 ValueSet DefinedValues;
109 ForwardRefMap ForwardRefs;
110 bool is_inline;
Chris Lattner1018c242010-06-21 23:14:47 +0000111 unsigned indent_level;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000112
113 public:
114 static char ID;
David Greene71847812009-07-14 20:18:05 +0000115 explicit CppWriter(formatted_raw_ostream &o) :
Owen Anderson90c579d2010-08-06 18:33:48 +0000116 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
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
Chris Lattner1018c242010-06-21 23:14:47 +0000133
134 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
135 inline void in() { indent_level++; }
136 inline void out() { if (indent_level >0) indent_level--; }
137
Anton Korobeynikov50276522008-04-23 22:29:24 +0000138 private:
139 void printLinkageType(GlobalValue::LinkageTypes LT);
140 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000141 void printCallingConv(CallingConv::ID cc);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000142 void printEscapedString(const std::string& str);
143 void printCFP(const ConstantFP* CFP);
144
145 std::string getCppName(const Type* val);
146 inline void printCppName(const Type* val);
147
148 std::string getCppName(const Value* val);
149 inline void printCppName(const Value* val);
150
Devang Patel05988662008-09-25 21:00:45 +0000151 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000152 bool printTypeInternal(const Type* Ty);
153 inline void printType(const Type* Ty);
154 void printTypes(const Module* M);
155
156 void printConstant(const Constant *CPV);
157 void printConstants(const Module* M);
158
159 void printVariableUses(const GlobalVariable *GV);
160 void printVariableHead(const GlobalVariable *GV);
161 void printVariableBody(const GlobalVariable *GV);
162
163 void printFunctionUses(const Function *F);
164 void printFunctionHead(const Function *F);
165 void printFunctionBody(const Function *F);
166 void printInstruction(const Instruction *I, const std::string& bbname);
167 std::string getOpName(Value*);
168
169 void printModuleBody();
170 };
Chris Lattner7e6d7452010-06-21 23:12:56 +0000171} // end anonymous namespace.
Anton Korobeynikov50276522008-04-23 22:29:24 +0000172
Chris Lattner1018c242010-06-21 23:14:47 +0000173formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
174 Out << '\n';
Chris Lattner7e6d7452010-06-21 23:12:56 +0000175 if (delta >= 0 || indent_level >= unsigned(-delta))
176 indent_level += delta;
Chris Lattner1018c242010-06-21 23:14:47 +0000177 Out.indent(indent_level);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000178 return Out;
179}
180
Chris Lattner7e6d7452010-06-21 23:12:56 +0000181static inline void 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
187static std::string getTypePrefix(const Type *Ty) {
188 switch (Ty->getTypeID()) {
189 case Type::VoidTyID: return "void_";
190 case Type::IntegerTyID:
191 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
192 case Type::FloatTyID: return "float_";
193 case Type::DoubleTyID: return "double_";
194 case Type::LabelTyID: return "label_";
195 case Type::FunctionTyID: return "func_";
196 case Type::StructTyID: return "struct_";
197 case Type::ArrayTyID: return "array_";
198 case Type::PointerTyID: return "ptr_";
199 case Type::VectorTyID: return "packed_";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000200 default: return "other_";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000201 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000202 return "unknown_";
203}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000204
Chris Lattner7e6d7452010-06-21 23:12:56 +0000205void CppWriter::error(const std::string& msg) {
206 report_fatal_error(msg);
207}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000208
Chris Lattner7e6d7452010-06-21 23:12:56 +0000209// printCFP - Print a floating point constant .. very carefully :)
210// This makes sure that conversion to/from floating yields the same binary
211// result so that we don't lose precision.
212void CppWriter::printCFP(const ConstantFP *CFP) {
213 bool ignored;
214 APFloat APF = APFloat(CFP->getValueAPF()); // copy
215 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
216 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
217 Out << "ConstantFP::get(mod->getContext(), ";
218 Out << "APFloat(";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000219#if HAVE_PRINTF_A
Chris Lattner7e6d7452010-06-21 23:12:56 +0000220 char Buffer[100];
221 sprintf(Buffer, "%A", APF.convertToDouble());
222 if ((!strncmp(Buffer, "0x", 2) ||
223 !strncmp(Buffer, "-0x", 3) ||
224 !strncmp(Buffer, "+0x", 3)) &&
225 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
226 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
227 Out << "BitsToDouble(" << Buffer << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000228 else
Chris Lattner7e6d7452010-06-21 23:12:56 +0000229 Out << "BitsToFloat((float)" << Buffer << ")";
230 Out << ")";
231 } else {
232#endif
233 std::string StrVal = ftostr(CFP->getValueAPF());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000234
Chris Lattner7e6d7452010-06-21 23:12:56 +0000235 while (StrVal[0] == ' ')
236 StrVal.erase(StrVal.begin());
237
238 // Check to make sure that the stringized number is not some string like
239 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
240 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
241 ((StrVal[0] == '-' || StrVal[0] == '+') &&
242 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
243 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
244 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
245 Out << StrVal;
246 else
247 Out << StrVal << "f";
248 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
249 Out << "BitsToDouble(0x"
250 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
251 << "ULL) /* " << StrVal << " */";
252 else
253 Out << "BitsToFloat(0x"
254 << utohexstr((uint32_t)CFP->getValueAPF().
255 bitcastToAPInt().getZExtValue())
256 << "U) /* " << StrVal << " */";
257 Out << ")";
258#if HAVE_PRINTF_A
259 }
260#endif
261 Out << ")";
262}
263
264void CppWriter::printCallingConv(CallingConv::ID cc){
265 // Print the calling convention.
266 switch (cc) {
267 case CallingConv::C: Out << "CallingConv::C"; break;
268 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
269 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
270 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
271 default: Out << cc; break;
272 }
273}
274
275void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
276 switch (LT) {
277 case GlobalValue::InternalLinkage:
278 Out << "GlobalValue::InternalLinkage"; break;
279 case GlobalValue::PrivateLinkage:
280 Out << "GlobalValue::PrivateLinkage"; break;
281 case GlobalValue::LinkerPrivateLinkage:
282 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Bill Wendling5e721d72010-07-01 21:55:59 +0000283 case GlobalValue::LinkerPrivateWeakLinkage:
284 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
Bill Wendling55ae5152010-08-20 22:05:50 +0000285 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
286 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000287 case GlobalValue::AvailableExternallyLinkage:
288 Out << "GlobalValue::AvailableExternallyLinkage "; break;
289 case GlobalValue::LinkOnceAnyLinkage:
290 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
291 case GlobalValue::LinkOnceODRLinkage:
292 Out << "GlobalValue::LinkOnceODRLinkage "; break;
293 case GlobalValue::WeakAnyLinkage:
294 Out << "GlobalValue::WeakAnyLinkage"; break;
295 case GlobalValue::WeakODRLinkage:
296 Out << "GlobalValue::WeakODRLinkage"; break;
297 case GlobalValue::AppendingLinkage:
298 Out << "GlobalValue::AppendingLinkage"; break;
299 case GlobalValue::ExternalLinkage:
300 Out << "GlobalValue::ExternalLinkage"; break;
301 case GlobalValue::DLLImportLinkage:
302 Out << "GlobalValue::DLLImportLinkage"; break;
303 case GlobalValue::DLLExportLinkage:
304 Out << "GlobalValue::DLLExportLinkage"; break;
305 case GlobalValue::ExternalWeakLinkage:
306 Out << "GlobalValue::ExternalWeakLinkage"; break;
307 case GlobalValue::CommonLinkage:
308 Out << "GlobalValue::CommonLinkage"; break;
309 }
310}
311
312void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
313 switch (VisType) {
314 default: llvm_unreachable("Unknown GVar visibility");
315 case GlobalValue::DefaultVisibility:
316 Out << "GlobalValue::DefaultVisibility";
317 break;
318 case GlobalValue::HiddenVisibility:
319 Out << "GlobalValue::HiddenVisibility";
320 break;
321 case GlobalValue::ProtectedVisibility:
322 Out << "GlobalValue::ProtectedVisibility";
323 break;
324 }
325}
326
327// printEscapedString - Print each character of the specified string, escaping
328// it if it is not printable or if it is an escape char.
329void CppWriter::printEscapedString(const std::string &Str) {
330 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
331 unsigned char C = Str[i];
332 if (isprint(C) && C != '"' && C != '\\') {
333 Out << C;
334 } else {
335 Out << "\\x"
336 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
337 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
338 }
339 }
340}
341
342std::string CppWriter::getCppName(const Type* Ty) {
343 // First, handle the primitive types .. easy
344 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
345 switch (Ty->getTypeID()) {
346 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
347 case Type::IntegerTyID: {
348 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
349 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
350 }
351 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
352 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
353 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
354 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
Dale Johannesenbb811a22010-09-10 20:55:01 +0000355 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000356 default:
357 error("Invalid primitive type");
358 break;
359 }
360 // shouldn't be returned, but make it sensible
361 return "Type::getVoidTy(mod->getContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000362 }
363
Chris Lattner7e6d7452010-06-21 23:12:56 +0000364 // Now, see if we've seen the type before and return that
365 TypeMap::iterator I = TypeNames.find(Ty);
366 if (I != TypeNames.end())
367 return I->second;
368
369 // Okay, let's build a new name for this type. Start with a prefix
370 const char* prefix = 0;
371 switch (Ty->getTypeID()) {
372 case Type::FunctionTyID: prefix = "FuncTy_"; break;
373 case Type::StructTyID: prefix = "StructTy_"; break;
374 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
375 case Type::PointerTyID: prefix = "PointerTy_"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000376 case Type::VectorTyID: prefix = "VectorTy_"; break;
377 default: prefix = "OtherTy_"; break; // prevent breakage
Anton Korobeynikov50276522008-04-23 22:29:24 +0000378 }
379
Chris Lattner7e6d7452010-06-21 23:12:56 +0000380 // See if the type has a name in the symboltable and build accordingly
Chris Lattner7e6d7452010-06-21 23:12:56 +0000381 std::string name;
Chris Lattner1afcace2011-07-09 17:41:24 +0000382 if (const StructType *STy = dyn_cast<StructType>(Ty))
383 if (STy->hasName())
384 name = STy->getName();
385
386 if (name.empty())
387 name = utostr(uniqueNum++);
388
389 name = std::string(prefix) + name;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000390 sanitize(name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000391
Chris Lattner7e6d7452010-06-21 23:12:56 +0000392 // Save the name
393 return TypeNames[Ty] = name;
394}
395
396void CppWriter::printCppName(const Type* Ty) {
397 printEscapedString(getCppName(Ty));
398}
399
400std::string CppWriter::getCppName(const Value* val) {
401 std::string name;
402 ValueMap::iterator I = ValueNames.find(val);
403 if (I != ValueNames.end() && I->first == val)
404 return I->second;
405
406 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
407 name = std::string("gvar_") +
408 getTypePrefix(GV->getType()->getElementType());
409 } else if (isa<Function>(val)) {
410 name = std::string("func_");
411 } else if (const Constant* C = dyn_cast<Constant>(val)) {
412 name = std::string("const_") + getTypePrefix(C->getType());
413 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
414 if (is_inline) {
415 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
416 Function::const_arg_iterator(Arg)) + 1;
417 name = std::string("arg_") + utostr(argNum);
418 NameSet::iterator NI = UsedNames.find(name);
419 if (NI != UsedNames.end())
420 name += std::string("_") + utostr(uniqueNum++);
421 UsedNames.insert(name);
422 return ValueNames[val] = name;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000423 } else {
424 name = getTypePrefix(val->getType());
425 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000426 } else {
427 name = getTypePrefix(val->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000428 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000429 if (val->hasName())
430 name += val->getName();
431 else
432 name += utostr(uniqueNum++);
433 sanitize(name);
434 NameSet::iterator NI = UsedNames.find(name);
435 if (NI != UsedNames.end())
436 name += std::string("_") + utostr(uniqueNum++);
437 UsedNames.insert(name);
438 return ValueNames[val] = name;
439}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000440
Chris Lattner7e6d7452010-06-21 23:12:56 +0000441void CppWriter::printCppName(const Value* val) {
442 printEscapedString(getCppName(val));
443}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000444
Chris Lattner7e6d7452010-06-21 23:12:56 +0000445void CppWriter::printAttributes(const AttrListPtr &PAL,
446 const std::string &name) {
447 Out << "AttrListPtr " << name << "_PAL;";
448 nl(Out);
449 if (!PAL.isEmpty()) {
450 Out << '{'; in(); nl(Out);
451 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
452 Out << "AttributeWithIndex PAWI;"; nl(Out);
453 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
454 unsigned index = PAL.getSlot(i).Index;
455 Attributes attrs = PAL.getSlot(i).Attrs;
456 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
Chris Lattneracca9552009-01-13 07:22:22 +0000457#define HANDLE_ATTR(X) \
Chris Lattner7e6d7452010-06-21 23:12:56 +0000458 if (attrs & Attribute::X) \
459 Out << " | Attribute::" #X; \
460 attrs &= ~Attribute::X;
461
462 HANDLE_ATTR(SExt);
463 HANDLE_ATTR(ZExt);
464 HANDLE_ATTR(NoReturn);
465 HANDLE_ATTR(InReg);
466 HANDLE_ATTR(StructRet);
467 HANDLE_ATTR(NoUnwind);
468 HANDLE_ATTR(NoAlias);
469 HANDLE_ATTR(ByVal);
470 HANDLE_ATTR(Nest);
471 HANDLE_ATTR(ReadNone);
472 HANDLE_ATTR(ReadOnly);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000473 HANDLE_ATTR(NoInline);
474 HANDLE_ATTR(AlwaysInline);
475 HANDLE_ATTR(OptimizeForSize);
476 HANDLE_ATTR(StackProtect);
477 HANDLE_ATTR(StackProtectReq);
478 HANDLE_ATTR(NoCapture);
Eli Friedman32bb4df2010-07-16 18:47:20 +0000479 HANDLE_ATTR(NoRedZone);
480 HANDLE_ATTR(NoImplicitFloat);
481 HANDLE_ATTR(Naked);
482 HANDLE_ATTR(InlineHint);
Chris Lattneracca9552009-01-13 07:22:22 +0000483#undef HANDLE_ATTR
Eli Friedman32bb4df2010-07-16 18:47:20 +0000484 if (attrs & Attribute::StackAlignment)
485 Out << " | Attribute::constructStackAlignmentFromInt("
486 << Attribute::getStackAlignmentFromAttrs(attrs)
487 << ")";
488 attrs &= ~Attribute::StackAlignment;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000489 assert(attrs == 0 && "Unhandled attribute!");
490 Out << ";";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000491 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000492 Out << "Attrs.push_back(PAWI);";
493 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000494 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000495 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
496 nl(Out);
497 out(); nl(Out);
498 Out << '}'; nl(Out);
499 }
500}
501
502bool CppWriter::printTypeInternal(const Type* Ty) {
503 // We don't print definitions for primitive types
504 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
505 return false;
506
507 // If we already defined this type, we don't need to define it again.
508 if (DefinedTypes.find(Ty) != DefinedTypes.end())
509 return false;
510
511 // Everything below needs the name for the type so get it now.
512 std::string typeName(getCppName(Ty));
513
514 // Search the type stack for recursion. If we find it, then generate this
515 // as an OpaqueType, but make sure not to do this multiple times because
516 // the type could appear in multiple places on the stack. Once the opaque
517 // definition is issued, it must not be re-issued. Consequently we have to
518 // check the UnresolvedTypes list as well.
519 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
520 Ty);
521 if (TI != TypeStack.end()) {
522 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
523 if (I == UnresolvedTypes.end()) {
524 Out << "PATypeHolder " << typeName;
525 Out << "_fwd = OpaqueType::get(mod->getContext());";
526 nl(Out);
527 UnresolvedTypes[Ty] = typeName;
528 }
529 return true;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000530 }
531
Chris Lattner7e6d7452010-06-21 23:12:56 +0000532 // We're going to print a derived type which, by definition, contains other
533 // types. So, push this one we're printing onto the type stack to assist with
534 // recursive definitions.
535 TypeStack.push_back(Ty);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000536
Chris Lattner7e6d7452010-06-21 23:12:56 +0000537 // Print the type definition
538 switch (Ty->getTypeID()) {
539 case Type::FunctionTyID: {
540 const FunctionType* FT = cast<FunctionType>(Ty);
541 Out << "std::vector<const Type*>" << typeName << "_args;";
542 nl(Out);
543 FunctionType::param_iterator PI = FT->param_begin();
544 FunctionType::param_iterator PE = FT->param_end();
545 for (; PI != PE; ++PI) {
546 const Type* argTy = static_cast<const Type*>(*PI);
547 bool isForward = printTypeInternal(argTy);
548 std::string argName(getCppName(argTy));
549 Out << typeName << "_args.push_back(" << argName;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000550 if (isForward)
551 Out << "_fwd";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000552 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000553 nl(Out);
554 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000555 bool isForward = printTypeInternal(FT->getReturnType());
556 std::string retTypeName(getCppName(FT->getReturnType()));
557 Out << "FunctionType* " << typeName << " = FunctionType::get(";
558 in(); nl(Out) << "/*Result=*/" << retTypeName;
559 if (isForward)
560 Out << "_fwd";
561 Out << ",";
562 nl(Out) << "/*Params=*/" << typeName << "_args,";
563 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
564 out();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000565 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000566 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000567 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000568 case Type::StructTyID: {
569 const StructType* ST = cast<StructType>(Ty);
570 Out << "std::vector<const Type*>" << typeName << "_fields;";
571 nl(Out);
572 StructType::element_iterator EI = ST->element_begin();
573 StructType::element_iterator EE = ST->element_end();
574 for (; EI != EE; ++EI) {
575 const Type* fieldTy = static_cast<const Type*>(*EI);
576 bool isForward = printTypeInternal(fieldTy);
577 std::string fieldName(getCppName(fieldTy));
578 Out << typeName << "_fields.push_back(" << fieldName;
579 if (isForward)
580 Out << "_fwd";
581 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000582 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000583 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000584
585 Out << "StructType *" << typeName << " = ";
586 if (ST->isAnonymous()) {
587 Out << "StructType::get(" << "mod->getContext(), ";
588 } else {
589 Out << "StructType::createNamed(mod->getContext(), \"";
590 printEscapedString(ST->getName());
591 Out << "\");";
592 nl(Out);
593 Out << typeName << "->setBody(";
594 }
595 Out << typeName << "_fields, /*isPacked=*/"
Chris Lattner7e6d7452010-06-21 23:12:56 +0000596 << (ST->isPacked() ? "true" : "false") << ");";
597 nl(Out);
598 break;
599 }
600 case Type::ArrayTyID: {
601 const ArrayType* AT = cast<ArrayType>(Ty);
602 const Type* ET = AT->getElementType();
603 bool isForward = printTypeInternal(ET);
604 std::string elemName(getCppName(ET));
605 Out << "ArrayType* " << typeName << " = ArrayType::get("
606 << elemName << (isForward ? "_fwd" : "")
607 << ", " << utostr(AT->getNumElements()) << ");";
608 nl(Out);
609 break;
610 }
611 case Type::PointerTyID: {
612 const PointerType* PT = cast<PointerType>(Ty);
613 const Type* ET = PT->getElementType();
614 bool isForward = printTypeInternal(ET);
615 std::string elemName(getCppName(ET));
616 Out << "PointerType* " << typeName << " = PointerType::get("
617 << elemName << (isForward ? "_fwd" : "")
618 << ", " << utostr(PT->getAddressSpace()) << ");";
619 nl(Out);
620 break;
621 }
622 case Type::VectorTyID: {
623 const VectorType* PT = cast<VectorType>(Ty);
624 const Type* ET = PT->getElementType();
625 bool isForward = printTypeInternal(ET);
626 std::string elemName(getCppName(ET));
627 Out << "VectorType* " << typeName << " = VectorType::get("
628 << elemName << (isForward ? "_fwd" : "")
629 << ", " << utostr(PT->getNumElements()) << ");";
630 nl(Out);
631 break;
632 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000633 default:
634 error("Invalid TypeID");
635 }
636
Chris Lattner7e6d7452010-06-21 23:12:56 +0000637 // Pop us off the type stack
638 TypeStack.pop_back();
639
640 // Indicate that this type is now defined.
641 DefinedTypes.insert(Ty);
642
643 // Early resolve as many unresolved types as possible. Search the unresolved
644 // types map for the type we just printed. Now that its definition is complete
645 // we can resolve any previous references to it. This prevents a cascade of
646 // unresolved types.
647 TypeMap::iterator I = UnresolvedTypes.find(Ty);
648 if (I != UnresolvedTypes.end()) {
649 Out << "cast<OpaqueType>(" << I->second
650 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
651 nl(Out);
652 Out << I->second << " = cast<";
653 switch (Ty->getTypeID()) {
654 case Type::FunctionTyID: Out << "FunctionType"; break;
655 case Type::ArrayTyID: Out << "ArrayType"; break;
656 case Type::StructTyID: Out << "StructType"; break;
657 case Type::VectorTyID: Out << "VectorType"; break;
658 case Type::PointerTyID: Out << "PointerType"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000659 default: Out << "NoSuchDerivedType"; break;
660 }
661 Out << ">(" << I->second << "_fwd.get());";
662 nl(Out); nl(Out);
663 UnresolvedTypes.erase(I);
664 }
665
666 // Finally, separate the type definition from other with a newline.
667 nl(Out);
668
669 // We weren't a recursive type
670 return false;
671}
672
673// Prints a type definition. Returns true if it could not resolve all the
674// types in the definition but had to use a forward reference.
675void CppWriter::printType(const Type* Ty) {
676 assert(TypeStack.empty());
677 TypeStack.clear();
678 printTypeInternal(Ty);
679 assert(TypeStack.empty());
680}
681
682void CppWriter::printTypes(const Module* M) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000683 // Add all of the global variables to the value table.
Chris Lattner7e6d7452010-06-21 23:12:56 +0000684 for (Module::const_global_iterator I = TheModule->global_begin(),
685 E = TheModule->global_end(); I != E; ++I) {
686 if (I->hasInitializer())
687 printType(I->getInitializer()->getType());
688 printType(I->getType());
689 }
690
691 // Add all the functions to the table
692 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
693 FI != FE; ++FI) {
694 printType(FI->getReturnType());
695 printType(FI->getFunctionType());
696 // Add all the function arguments
697 for (Function::const_arg_iterator AI = FI->arg_begin(),
698 AE = FI->arg_end(); AI != AE; ++AI) {
699 printType(AI->getType());
700 }
701
702 // Add all of the basic blocks and instructions
703 for (Function::const_iterator BB = FI->begin(),
704 E = FI->end(); BB != E; ++BB) {
705 printType(BB->getType());
706 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
707 ++I) {
708 printType(I->getType());
709 for (unsigned i = 0; i < I->getNumOperands(); ++i)
710 printType(I->getOperand(i)->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000711 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000712 }
713 }
714}
715
716
717// printConstant - Print out a constant pool entry...
718void CppWriter::printConstant(const Constant *CV) {
719 // First, if the constant is actually a GlobalValue (variable or function)
720 // or its already in the constant list then we've printed it already and we
721 // can just return.
722 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
723 return;
724
725 std::string constName(getCppName(CV));
726 std::string typeName(getCppName(CV->getType()));
727
728 if (isa<GlobalValue>(CV)) {
729 // Skip variables and functions, we emit them elsewhere
730 return;
731 }
732
733 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
734 std::string constValue = CI->getValue().toString(10, true);
735 Out << "ConstantInt* " << constName
736 << " = ConstantInt::get(mod->getContext(), APInt("
737 << cast<IntegerType>(CI->getType())->getBitWidth()
738 << ", StringRef(\"" << constValue << "\"), 10));";
739 } else if (isa<ConstantAggregateZero>(CV)) {
740 Out << "ConstantAggregateZero* " << constName
741 << " = ConstantAggregateZero::get(" << typeName << ");";
742 } else if (isa<ConstantPointerNull>(CV)) {
743 Out << "ConstantPointerNull* " << constName
744 << " = ConstantPointerNull::get(" << typeName << ");";
745 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
746 Out << "ConstantFP* " << constName << " = ";
747 printCFP(CFP);
748 Out << ";";
749 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
750 if (CA->isString() &&
751 CA->getType()->getElementType() ==
752 Type::getInt8Ty(CA->getContext())) {
753 Out << "Constant* " << constName <<
754 " = ConstantArray::get(mod->getContext(), \"";
755 std::string tmp = CA->getAsString();
756 bool nullTerminate = false;
757 if (tmp[tmp.length()-1] == 0) {
758 tmp.erase(tmp.length()-1);
759 nullTerminate = true;
760 }
761 printEscapedString(tmp);
762 // Determine if we want null termination or not.
763 if (nullTerminate)
764 Out << "\", true"; // Indicate that the null terminator should be
765 // added.
766 else
767 Out << "\", false";// No null terminator
768 Out << ");";
769 } else {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000770 Out << "std::vector<Constant*> " << constName << "_elems;";
771 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000772 unsigned N = CA->getNumOperands();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000773 for (unsigned i = 0; i < N; ++i) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000774 printConstant(CA->getOperand(i)); // recurse to print operands
Anton Korobeynikov50276522008-04-23 22:29:24 +0000775 Out << constName << "_elems.push_back("
Chris Lattner7e6d7452010-06-21 23:12:56 +0000776 << getCppName(CA->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000777 nl(Out);
778 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000779 Out << "Constant* " << constName << " = ConstantArray::get("
Anton Korobeynikov50276522008-04-23 22:29:24 +0000780 << typeName << ", " << constName << "_elems);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000781 }
782 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
783 Out << "std::vector<Constant*> " << constName << "_fields;";
784 nl(Out);
785 unsigned N = CS->getNumOperands();
786 for (unsigned i = 0; i < N; i++) {
787 printConstant(CS->getOperand(i));
788 Out << constName << "_fields.push_back("
789 << getCppName(CS->getOperand(i)) << ");";
790 nl(Out);
791 }
792 Out << "Constant* " << constName << " = ConstantStruct::get("
793 << typeName << ", " << constName << "_fields);";
794 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
795 Out << "std::vector<Constant*> " << constName << "_elems;";
796 nl(Out);
797 unsigned N = CP->getNumOperands();
798 for (unsigned i = 0; i < N; ++i) {
799 printConstant(CP->getOperand(i));
800 Out << constName << "_elems.push_back("
801 << getCppName(CP->getOperand(i)) << ");";
802 nl(Out);
803 }
804 Out << "Constant* " << constName << " = ConstantVector::get("
805 << typeName << ", " << constName << "_elems);";
806 } else if (isa<UndefValue>(CV)) {
807 Out << "UndefValue* " << constName << " = UndefValue::get("
808 << typeName << ");";
809 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
810 if (CE->getOpcode() == Instruction::GetElementPtr) {
811 Out << "std::vector<Constant*> " << constName << "_indices;";
812 nl(Out);
813 printConstant(CE->getOperand(0));
814 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
815 printConstant(CE->getOperand(i));
816 Out << constName << "_indices.push_back("
817 << getCppName(CE->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000818 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000819 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000820 Out << "Constant* " << constName
821 << " = ConstantExpr::getGetElementPtr("
822 << getCppName(CE->getOperand(0)) << ", "
823 << "&" << constName << "_indices[0], "
824 << constName << "_indices.size()"
825 << ");";
826 } else if (CE->isCast()) {
827 printConstant(CE->getOperand(0));
828 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
829 switch (CE->getOpcode()) {
830 default: llvm_unreachable("Invalid cast opcode");
831 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
832 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
833 case Instruction::SExt: Out << "Instruction::SExt"; break;
834 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
835 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
836 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
837 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
838 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
839 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
840 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
841 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
842 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
843 }
844 Out << ", " << getCppName(CE->getOperand(0)) << ", "
845 << getCppName(CE->getType()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000846 } else {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000847 unsigned N = CE->getNumOperands();
848 for (unsigned i = 0; i < N; ++i ) {
849 printConstant(CE->getOperand(i));
850 }
851 Out << "Constant* " << constName << " = ConstantExpr::";
852 switch (CE->getOpcode()) {
853 case Instruction::Add: Out << "getAdd("; break;
854 case Instruction::FAdd: Out << "getFAdd("; break;
855 case Instruction::Sub: Out << "getSub("; break;
856 case Instruction::FSub: Out << "getFSub("; break;
857 case Instruction::Mul: Out << "getMul("; break;
858 case Instruction::FMul: Out << "getFMul("; break;
859 case Instruction::UDiv: Out << "getUDiv("; break;
860 case Instruction::SDiv: Out << "getSDiv("; break;
861 case Instruction::FDiv: Out << "getFDiv("; break;
862 case Instruction::URem: Out << "getURem("; break;
863 case Instruction::SRem: Out << "getSRem("; break;
864 case Instruction::FRem: Out << "getFRem("; break;
865 case Instruction::And: Out << "getAnd("; break;
866 case Instruction::Or: Out << "getOr("; break;
867 case Instruction::Xor: Out << "getXor("; break;
868 case Instruction::ICmp:
869 Out << "getICmp(ICmpInst::ICMP_";
870 switch (CE->getPredicate()) {
871 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
872 case ICmpInst::ICMP_NE: Out << "NE"; break;
873 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
874 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
875 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
876 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
877 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
878 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
879 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
880 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
881 default: error("Invalid ICmp Predicate");
882 }
883 break;
884 case Instruction::FCmp:
885 Out << "getFCmp(FCmpInst::FCMP_";
886 switch (CE->getPredicate()) {
887 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
888 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
889 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
890 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
891 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
892 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
893 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
894 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
895 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
896 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
897 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
898 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
899 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
900 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
901 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
902 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
903 default: error("Invalid FCmp Predicate");
904 }
905 break;
906 case Instruction::Shl: Out << "getShl("; break;
907 case Instruction::LShr: Out << "getLShr("; break;
908 case Instruction::AShr: Out << "getAShr("; break;
909 case Instruction::Select: Out << "getSelect("; break;
910 case Instruction::ExtractElement: Out << "getExtractElement("; break;
911 case Instruction::InsertElement: Out << "getInsertElement("; break;
912 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
913 default:
914 error("Invalid constant expression");
915 break;
916 }
917 Out << getCppName(CE->getOperand(0));
918 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
919 Out << ", " << getCppName(CE->getOperand(i));
920 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000921 }
Chris Lattner32848772010-06-21 23:19:36 +0000922 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
923 Out << "Constant* " << constName << " = ";
924 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000925 } else {
926 error("Bad Constant");
927 Out << "Constant* " << constName << " = 0; ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000928 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000929 nl(Out);
930}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000931
Chris Lattner7e6d7452010-06-21 23:12:56 +0000932void CppWriter::printConstants(const Module* M) {
933 // Traverse all the global variables looking for constant initializers
934 for (Module::const_global_iterator I = TheModule->global_begin(),
935 E = TheModule->global_end(); I != E; ++I)
936 if (I->hasInitializer())
937 printConstant(I->getInitializer());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000938
Chris Lattner7e6d7452010-06-21 23:12:56 +0000939 // Traverse the LLVM functions looking for constants
940 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
941 FI != FE; ++FI) {
942 // Add all of the basic blocks and instructions
943 for (Function::const_iterator BB = FI->begin(),
944 E = FI->end(); BB != E; ++BB) {
945 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
946 ++I) {
947 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
948 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
949 printConstant(C);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000950 }
951 }
952 }
953 }
954 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000955}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000956
Chris Lattner7e6d7452010-06-21 23:12:56 +0000957void CppWriter::printVariableUses(const GlobalVariable *GV) {
958 nl(Out) << "// Type Definitions";
959 nl(Out);
960 printType(GV->getType());
961 if (GV->hasInitializer()) {
Jay Foad7d715df2011-06-19 18:37:11 +0000962 const Constant *Init = GV->getInitializer();
Chris Lattner7e6d7452010-06-21 23:12:56 +0000963 printType(Init->getType());
Jay Foad7d715df2011-06-19 18:37:11 +0000964 if (const Function *F = dyn_cast<Function>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000965 nl(Out)<< "/ Function Declarations"; nl(Out);
966 printFunctionHead(F);
Jay Foad7d715df2011-06-19 18:37:11 +0000967 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000968 nl(Out) << "// Global Variable Declarations"; nl(Out);
969 printVariableHead(gv);
970
971 nl(Out) << "// Global Variable Definitions"; nl(Out);
972 printVariableBody(gv);
973 } else {
974 nl(Out) << "// Constant Definitions"; nl(Out);
975 printConstant(Init);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000976 }
977 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000978}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000979
Chris Lattner7e6d7452010-06-21 23:12:56 +0000980void CppWriter::printVariableHead(const GlobalVariable *GV) {
981 nl(Out) << "GlobalVariable* " << getCppName(GV);
982 if (is_inline) {
983 Out << " = mod->getGlobalVariable(mod->getContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000984 printEscapedString(GV->getName());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000985 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
986 nl(Out) << "if (!" << getCppName(GV) << ") {";
987 in(); nl(Out) << getCppName(GV);
988 }
989 Out << " = new GlobalVariable(/*Module=*/*mod, ";
990 nl(Out) << "/*Type=*/";
991 printCppName(GV->getType()->getElementType());
992 Out << ",";
993 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
994 Out << ",";
995 nl(Out) << "/*Linkage=*/";
996 printLinkageType(GV->getLinkage());
997 Out << ",";
998 nl(Out) << "/*Initializer=*/0, ";
999 if (GV->hasInitializer()) {
1000 Out << "// has initializer, specified below";
1001 }
1002 nl(Out) << "/*Name=*/\"";
1003 printEscapedString(GV->getName());
1004 Out << "\");";
1005 nl(Out);
1006
1007 if (GV->hasSection()) {
1008 printCppName(GV);
1009 Out << "->setSection(\"";
1010 printEscapedString(GV->getSection());
Owen Anderson16a412e2009-07-10 16:42:19 +00001011 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001012 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001013 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001014 if (GV->getAlignment()) {
1015 printCppName(GV);
1016 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001017 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001018 }
1019 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1020 printCppName(GV);
1021 Out << "->setVisibility(";
1022 printVisibilityType(GV->getVisibility());
1023 Out << ");";
1024 nl(Out);
1025 }
1026 if (GV->isThreadLocal()) {
1027 printCppName(GV);
1028 Out << "->setThreadLocal(true);";
1029 nl(Out);
1030 }
1031 if (is_inline) {
1032 out(); Out << "}"; nl(Out);
1033 }
1034}
1035
1036void CppWriter::printVariableBody(const GlobalVariable *GV) {
1037 if (GV->hasInitializer()) {
1038 printCppName(GV);
1039 Out << "->setInitializer(";
1040 Out << getCppName(GV->getInitializer()) << ");";
1041 nl(Out);
1042 }
1043}
1044
1045std::string CppWriter::getOpName(Value* V) {
1046 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1047 return getCppName(V);
1048
1049 // See if its alread in the map of forward references, if so just return the
1050 // name we already set up for it
1051 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1052 if (I != ForwardRefs.end())
1053 return I->second;
1054
1055 // This is a new forward reference. Generate a unique name for it
1056 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1057
1058 // Yes, this is a hack. An Argument is the smallest instantiable value that
1059 // we can make as a placeholder for the real value. We'll replace these
1060 // Argument instances later.
1061 Out << "Argument* " << result << " = new Argument("
1062 << getCppName(V->getType()) << ");";
1063 nl(Out);
1064 ForwardRefs[V] = result;
1065 return result;
1066}
1067
1068// printInstruction - This member is called for each Instruction in a function.
1069void CppWriter::printInstruction(const Instruction *I,
1070 const std::string& bbname) {
1071 std::string iName(getCppName(I));
1072
1073 // Before we emit this instruction, we need to take care of generating any
1074 // forward references. So, we get the names of all the operands in advance
1075 const unsigned Ops(I->getNumOperands());
1076 std::string* opNames = new std::string[Ops];
Chris Lattner32848772010-06-21 23:19:36 +00001077 for (unsigned i = 0; i < Ops; i++)
Chris Lattner7e6d7452010-06-21 23:12:56 +00001078 opNames[i] = getOpName(I->getOperand(i));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001079
Chris Lattner7e6d7452010-06-21 23:12:56 +00001080 switch (I->getOpcode()) {
1081 default:
1082 error("Invalid instruction");
1083 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001084
Chris Lattner7e6d7452010-06-21 23:12:56 +00001085 case Instruction::Ret: {
1086 const ReturnInst* ret = cast<ReturnInst>(I);
1087 Out << "ReturnInst::Create(mod->getContext(), "
1088 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1089 break;
1090 }
1091 case Instruction::Br: {
1092 const BranchInst* br = cast<BranchInst>(I);
1093 Out << "BranchInst::Create(" ;
Chris Lattner32848772010-06-21 23:19:36 +00001094 if (br->getNumOperands() == 3) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001095 Out << opNames[2] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001096 << opNames[1] << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001097 << opNames[0] << ", ";
1098
1099 } else if (br->getNumOperands() == 1) {
1100 Out << opNames[0] << ", ";
1101 } else {
1102 error("Branch with 2 operands?");
1103 }
1104 Out << bbname << ");";
1105 break;
1106 }
1107 case Instruction::Switch: {
1108 const SwitchInst *SI = cast<SwitchInst>(I);
1109 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1110 << opNames[0] << ", "
1111 << opNames[1] << ", "
1112 << SI->getNumCases() << ", " << bbname << ");";
1113 nl(Out);
1114 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
1115 Out << iName << "->addCase("
1116 << opNames[i] << ", "
1117 << opNames[i+1] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001118 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001119 }
1120 break;
1121 }
1122 case Instruction::IndirectBr: {
1123 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1124 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1125 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1126 nl(Out);
1127 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1128 Out << iName << "->addDestination(" << opNames[i] << ");";
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 = 0; i < inv->getNumArgOperands(); ++i) {
1138 Out << iName << "_params.push_back("
1139 << getOpName(inv->getArgOperand(i)) << ");";
1140 nl(Out);
1141 }
1142 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1143 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1144 << getOpName(inv->getCalledFunction()) << ", "
1145 << getOpName(inv->getNormalDest()) << ", "
1146 << getOpName(inv->getUnwindDest()) << ", "
1147 << iName << "_params.begin(), "
1148 << iName << "_params.end(), \"";
1149 printEscapedString(inv->getName());
1150 Out << "\", " << bbname << ");";
1151 nl(Out) << iName << "->setCallingConv(";
1152 printCallingConv(inv->getCallingConv());
1153 Out << ");";
1154 printAttributes(inv->getAttributes(), iName);
1155 Out << iName << "->setAttributes(" << iName << "_PAL);";
1156 nl(Out);
1157 break;
1158 }
1159 case Instruction::Unwind: {
1160 Out << "new UnwindInst("
1161 << bbname << ");";
1162 break;
1163 }
1164 case Instruction::Unreachable: {
1165 Out << "new UnreachableInst("
1166 << "mod->getContext(), "
1167 << bbname << ");";
1168 break;
1169 }
1170 case Instruction::Add:
1171 case Instruction::FAdd:
1172 case Instruction::Sub:
1173 case Instruction::FSub:
1174 case Instruction::Mul:
1175 case Instruction::FMul:
1176 case Instruction::UDiv:
1177 case Instruction::SDiv:
1178 case Instruction::FDiv:
1179 case Instruction::URem:
1180 case Instruction::SRem:
1181 case Instruction::FRem:
1182 case Instruction::And:
1183 case Instruction::Or:
1184 case Instruction::Xor:
1185 case Instruction::Shl:
1186 case Instruction::LShr:
1187 case Instruction::AShr:{
1188 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1189 switch (I->getOpcode()) {
1190 case Instruction::Add: Out << "Instruction::Add"; break;
1191 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1192 case Instruction::Sub: Out << "Instruction::Sub"; break;
1193 case Instruction::FSub: Out << "Instruction::FSub"; break;
1194 case Instruction::Mul: Out << "Instruction::Mul"; break;
1195 case Instruction::FMul: Out << "Instruction::FMul"; break;
1196 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1197 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1198 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1199 case Instruction::URem:Out << "Instruction::URem"; break;
1200 case Instruction::SRem:Out << "Instruction::SRem"; break;
1201 case Instruction::FRem:Out << "Instruction::FRem"; break;
1202 case Instruction::And: Out << "Instruction::And"; break;
1203 case Instruction::Or: Out << "Instruction::Or"; break;
1204 case Instruction::Xor: Out << "Instruction::Xor"; break;
1205 case Instruction::Shl: Out << "Instruction::Shl"; break;
1206 case Instruction::LShr:Out << "Instruction::LShr"; break;
1207 case Instruction::AShr:Out << "Instruction::AShr"; break;
1208 default: Out << "Instruction::BadOpCode"; break;
1209 }
1210 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1211 printEscapedString(I->getName());
1212 Out << "\", " << bbname << ");";
1213 break;
1214 }
1215 case Instruction::FCmp: {
1216 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1217 switch (cast<FCmpInst>(I)->getPredicate()) {
1218 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1219 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1220 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1221 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1222 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1223 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1224 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1225 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1226 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1227 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1228 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1229 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1230 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1231 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1232 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1233 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1234 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1235 }
1236 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1237 printEscapedString(I->getName());
1238 Out << "\");";
1239 break;
1240 }
1241 case Instruction::ICmp: {
1242 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1243 switch (cast<ICmpInst>(I)->getPredicate()) {
1244 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1245 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1246 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1247 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1248 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1249 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1250 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1251 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1252 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1253 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1254 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1255 }
1256 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1257 printEscapedString(I->getName());
1258 Out << "\");";
1259 break;
1260 }
1261 case Instruction::Alloca: {
1262 const AllocaInst* allocaI = cast<AllocaInst>(I);
1263 Out << "AllocaInst* " << iName << " = new AllocaInst("
1264 << getCppName(allocaI->getAllocatedType()) << ", ";
1265 if (allocaI->isArrayAllocation())
1266 Out << opNames[0] << ", ";
1267 Out << "\"";
1268 printEscapedString(allocaI->getName());
1269 Out << "\", " << bbname << ");";
1270 if (allocaI->getAlignment())
1271 nl(Out) << iName << "->setAlignment("
1272 << allocaI->getAlignment() << ");";
1273 break;
1274 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001275 case Instruction::Load: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001276 const LoadInst* load = cast<LoadInst>(I);
1277 Out << "LoadInst* " << iName << " = new LoadInst("
1278 << opNames[0] << ", \"";
1279 printEscapedString(load->getName());
1280 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1281 << ", " << bbname << ");";
1282 break;
1283 }
1284 case Instruction::Store: {
1285 const StoreInst* store = cast<StoreInst>(I);
1286 Out << " new StoreInst("
1287 << opNames[0] << ", "
1288 << opNames[1] << ", "
1289 << (store->isVolatile() ? "true" : "false")
1290 << ", " << bbname << ");";
1291 break;
1292 }
1293 case Instruction::GetElementPtr: {
1294 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1295 if (gep->getNumOperands() <= 2) {
1296 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1297 << opNames[0];
1298 if (gep->getNumOperands() == 2)
1299 Out << ", " << opNames[1];
1300 } else {
1301 Out << "std::vector<Value*> " << iName << "_indices;";
1302 nl(Out);
1303 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1304 Out << iName << "_indices.push_back("
1305 << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001306 nl(Out);
1307 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001308 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1309 << opNames[0] << ", " << iName << "_indices.begin(), "
1310 << iName << "_indices.end()";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001311 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001312 Out << ", \"";
1313 printEscapedString(gep->getName());
1314 Out << "\", " << bbname << ");";
1315 break;
1316 }
1317 case Instruction::PHI: {
1318 const PHINode* phi = cast<PHINode>(I);
1319
1320 Out << "PHINode* " << iName << " = PHINode::Create("
Nicolas Geoffrayc6cf1972011-04-10 17:39:40 +00001321 << getCppName(phi->getType()) << ", "
Jay Foad3ecfc862011-03-30 11:28:46 +00001322 << phi->getNumIncomingValues() << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001323 printEscapedString(phi->getName());
1324 Out << "\", " << bbname << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001325 nl(Out);
Jay Foadc1371202011-06-20 14:18:48 +00001326 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001327 Out << iName << "->addIncoming("
Jay Foadc1371202011-06-20 14:18:48 +00001328 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
Jay Foad95c3e482011-06-23 09:09:15 +00001329 << getOpName(phi->getIncomingBlock(i)) << ");";
Chris Lattner627b4702009-10-27 21:24:48 +00001330 nl(Out);
Chris Lattner627b4702009-10-27 21:24:48 +00001331 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001332 break;
1333 }
1334 case Instruction::Trunc:
1335 case Instruction::ZExt:
1336 case Instruction::SExt:
1337 case Instruction::FPTrunc:
1338 case Instruction::FPExt:
1339 case Instruction::FPToUI:
1340 case Instruction::FPToSI:
1341 case Instruction::UIToFP:
1342 case Instruction::SIToFP:
1343 case Instruction::PtrToInt:
1344 case Instruction::IntToPtr:
1345 case Instruction::BitCast: {
1346 const CastInst* cst = cast<CastInst>(I);
1347 Out << "CastInst* " << iName << " = new ";
1348 switch (I->getOpcode()) {
1349 case Instruction::Trunc: Out << "TruncInst"; break;
1350 case Instruction::ZExt: Out << "ZExtInst"; break;
1351 case Instruction::SExt: Out << "SExtInst"; break;
1352 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1353 case Instruction::FPExt: Out << "FPExtInst"; break;
1354 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1355 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1356 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1357 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1358 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1359 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1360 case Instruction::BitCast: Out << "BitCastInst"; break;
1361 default: assert(!"Unreachable"); break;
1362 }
1363 Out << "(" << opNames[0] << ", "
1364 << getCppName(cst->getType()) << ", \"";
1365 printEscapedString(cst->getName());
1366 Out << "\", " << bbname << ");";
1367 break;
1368 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001369 case Instruction::Call: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001370 const CallInst* call = cast<CallInst>(I);
1371 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1372 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1373 << getCppName(ila->getFunctionType()) << ", \""
1374 << ila->getAsmString() << "\", \""
1375 << ila->getConstraintString() << "\","
1376 << (ila->hasSideEffects() ? "true" : "false") << ");";
1377 nl(Out);
1378 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001379 if (call->getNumArgOperands() > 1) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001380 Out << "std::vector<Value*> " << iName << "_params;";
1381 nl(Out);
Gabor Greif53ba5502010-07-02 19:08:46 +00001382 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
Gabor Greif63d024f2010-07-13 15:31:36 +00001383 Out << iName << "_params.push_back(" << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001384 nl(Out);
1385 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001386 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greifa3997812010-07-22 10:37:47 +00001387 << opNames[call->getNumArgOperands()] << ", "
1388 << iName << "_params.begin(), "
Bill Wendling22a5b292010-06-07 19:05:06 +00001389 << iName << "_params.end(), \"";
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001390 } else if (call->getNumArgOperands() == 1) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001391 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greif63d024f2010-07-13 15:31:36 +00001392 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001393 } else {
Gabor Greif63d024f2010-07-13 15:31:36 +00001394 Out << "CallInst* " << iName << " = CallInst::Create("
1395 << opNames[call->getNumArgOperands()] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001396 }
1397 printEscapedString(call->getName());
1398 Out << "\", " << bbname << ");";
1399 nl(Out) << iName << "->setCallingConv(";
1400 printCallingConv(call->getCallingConv());
1401 Out << ");";
1402 nl(Out) << iName << "->setTailCall("
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001403 << (call->isTailCall() ? "true" : "false");
Chris Lattner7e6d7452010-06-21 23:12:56 +00001404 Out << ");";
Gabor Greif135d7fe2010-07-02 19:26:28 +00001405 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001406 printAttributes(call->getAttributes(), iName);
1407 Out << iName << "->setAttributes(" << iName << "_PAL);";
1408 nl(Out);
1409 break;
1410 }
1411 case Instruction::Select: {
1412 const SelectInst* sel = cast<SelectInst>(I);
1413 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1414 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1415 printEscapedString(sel->getName());
1416 Out << "\", " << bbname << ");";
1417 break;
1418 }
1419 case Instruction::UserOp1:
1420 /// FALL THROUGH
1421 case Instruction::UserOp2: {
1422 /// FIXME: What should be done here?
1423 break;
1424 }
1425 case Instruction::VAArg: {
1426 const VAArgInst* va = cast<VAArgInst>(I);
1427 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1428 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1429 printEscapedString(va->getName());
1430 Out << "\", " << bbname << ");";
1431 break;
1432 }
1433 case Instruction::ExtractElement: {
1434 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1435 Out << "ExtractElementInst* " << getCppName(eei)
1436 << " = new ExtractElementInst(" << opNames[0]
1437 << ", " << opNames[1] << ", \"";
1438 printEscapedString(eei->getName());
1439 Out << "\", " << bbname << ");";
1440 break;
1441 }
1442 case Instruction::InsertElement: {
1443 const InsertElementInst* iei = cast<InsertElementInst>(I);
1444 Out << "InsertElementInst* " << getCppName(iei)
1445 << " = InsertElementInst::Create(" << opNames[0]
1446 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1447 printEscapedString(iei->getName());
1448 Out << "\", " << bbname << ");";
1449 break;
1450 }
1451 case Instruction::ShuffleVector: {
1452 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1453 Out << "ShuffleVectorInst* " << getCppName(svi)
1454 << " = new ShuffleVectorInst(" << opNames[0]
1455 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1456 printEscapedString(svi->getName());
1457 Out << "\", " << bbname << ");";
1458 break;
1459 }
1460 case Instruction::ExtractValue: {
1461 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1462 Out << "std::vector<unsigned> " << iName << "_indices;";
1463 nl(Out);
1464 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1465 Out << iName << "_indices.push_back("
1466 << evi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001467 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001468 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001469 Out << "ExtractValueInst* " << getCppName(evi)
1470 << " = ExtractValueInst::Create(" << opNames[0]
1471 << ", "
1472 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1473 printEscapedString(evi->getName());
1474 Out << "\", " << bbname << ");";
1475 break;
1476 }
1477 case Instruction::InsertValue: {
1478 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1479 Out << "std::vector<unsigned> " << iName << "_indices;";
1480 nl(Out);
1481 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1482 Out << iName << "_indices.push_back("
1483 << ivi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001484 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001485 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001486 Out << "InsertValueInst* " << getCppName(ivi)
1487 << " = InsertValueInst::Create(" << opNames[0]
1488 << ", " << opNames[1] << ", "
1489 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1490 printEscapedString(ivi->getName());
1491 Out << "\", " << bbname << ");";
1492 break;
1493 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001494 }
1495 DefinedValues.insert(I);
1496 nl(Out);
1497 delete [] opNames;
1498}
1499
Chris Lattner7e6d7452010-06-21 23:12:56 +00001500// Print out the types, constants and declarations needed by one function
1501void CppWriter::printFunctionUses(const Function* F) {
1502 nl(Out) << "// Type Definitions"; nl(Out);
1503 if (!is_inline) {
1504 // Print the function's return type
1505 printType(F->getReturnType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001506
Chris Lattner7e6d7452010-06-21 23:12:56 +00001507 // Print the function's function type
1508 printType(F->getFunctionType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001509
Chris Lattner7e6d7452010-06-21 23:12:56 +00001510 // Print the types of each of the function's arguments
Anton Korobeynikov50276522008-04-23 22:29:24 +00001511 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1512 AI != AE; ++AI) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001513 printType(AI->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001514 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001515 }
1516
Chris Lattner7e6d7452010-06-21 23:12:56 +00001517 // Print type definitions for every type referenced by an instruction and
1518 // make a note of any global values or constants that are referenced
1519 SmallPtrSet<GlobalValue*,64> gvs;
1520 SmallPtrSet<Constant*,64> consts;
1521 for (Function::const_iterator BB = F->begin(), BE = F->end();
1522 BB != BE; ++BB){
1523 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001524 I != E; ++I) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001525 // Print the type of the instruction itself
1526 printType(I->getType());
1527
1528 // Print the type of each of the instruction's operands
1529 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1530 Value* operand = I->getOperand(i);
1531 printType(operand->getType());
1532
1533 // If the operand references a GVal or Constant, make a note of it
1534 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1535 gvs.insert(GV);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001536 if (GenerationType != GenFunction)
1537 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1538 if (GVar->hasInitializer())
1539 consts.insert(GVar->getInitializer());
1540 } else if (Constant* C = dyn_cast<Constant>(operand)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001541 consts.insert(C);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001542 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1543 // If the operand references a GVal or Constant, make a note of it
1544 Value* operand = C->getOperand(j);
1545 printType(operand->getType());
1546 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1547 gvs.insert(GV);
1548 if (GenerationType != GenFunction)
1549 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1550 if (GVar->hasInitializer())
1551 consts.insert(GVar->getInitializer());
1552 }
1553 }
1554 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001555 }
1556 }
1557 }
1558
1559 // Print the function declarations for any functions encountered
1560 nl(Out) << "// Function Declarations"; nl(Out);
1561 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1562 I != E; ++I) {
1563 if (Function* Fun = dyn_cast<Function>(*I)) {
1564 if (!is_inline || Fun != F)
1565 printFunctionHead(Fun);
1566 }
1567 }
1568
1569 // Print the global variable declarations for any variables encountered
1570 nl(Out) << "// Global Variable Declarations"; nl(Out);
1571 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1572 I != E; ++I) {
1573 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1574 printVariableHead(F);
1575 }
1576
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001577 // Print the constants found
Chris Lattner7e6d7452010-06-21 23:12:56 +00001578 nl(Out) << "// Constant Definitions"; nl(Out);
1579 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1580 E = consts.end(); I != E; ++I) {
1581 printConstant(*I);
1582 }
1583
1584 // Process the global variables definitions now that all the constants have
1585 // been emitted. These definitions just couple the gvars with their constant
1586 // initializers.
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001587 if (GenerationType != GenFunction) {
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 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001594 }
1595}
1596
1597void CppWriter::printFunctionHead(const Function* F) {
1598 nl(Out) << "Function* " << getCppName(F);
1599 if (is_inline) {
1600 Out << " = mod->getFunction(\"";
1601 printEscapedString(F->getName());
1602 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1603 nl(Out) << "if (!" << getCppName(F) << ") {";
1604 nl(Out) << getCppName(F);
1605 }
1606 Out<< " = Function::Create(";
1607 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1608 nl(Out) << "/*Linkage=*/";
1609 printLinkageType(F->getLinkage());
1610 Out << ",";
1611 nl(Out) << "/*Name=*/\"";
1612 printEscapedString(F->getName());
1613 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1614 nl(Out,-1);
1615 printCppName(F);
1616 Out << "->setCallingConv(";
1617 printCallingConv(F->getCallingConv());
1618 Out << ");";
1619 nl(Out);
1620 if (F->hasSection()) {
1621 printCppName(F);
1622 Out << "->setSection(\"" << F->getSection() << "\");";
1623 nl(Out);
1624 }
1625 if (F->getAlignment()) {
1626 printCppName(F);
1627 Out << "->setAlignment(" << F->getAlignment() << ");";
1628 nl(Out);
1629 }
1630 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1631 printCppName(F);
1632 Out << "->setVisibility(";
1633 printVisibilityType(F->getVisibility());
1634 Out << ");";
1635 nl(Out);
1636 }
1637 if (F->hasGC()) {
1638 printCppName(F);
1639 Out << "->setGC(\"" << F->getGC() << "\");";
1640 nl(Out);
1641 }
1642 if (is_inline) {
1643 Out << "}";
1644 nl(Out);
1645 }
1646 printAttributes(F->getAttributes(), getCppName(F));
1647 printCppName(F);
1648 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1649 nl(Out);
1650}
1651
1652void CppWriter::printFunctionBody(const Function *F) {
1653 if (F->isDeclaration())
1654 return; // external functions have no bodies.
1655
1656 // Clear the DefinedValues and ForwardRefs maps because we can't have
1657 // cross-function forward refs
1658 ForwardRefs.clear();
1659 DefinedValues.clear();
1660
1661 // Create all the argument values
1662 if (!is_inline) {
1663 if (!F->arg_empty()) {
1664 Out << "Function::arg_iterator args = " << getCppName(F)
1665 << "->arg_begin();";
1666 nl(Out);
1667 }
1668 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1669 AI != AE; ++AI) {
1670 Out << "Value* " << getCppName(AI) << " = args++;";
1671 nl(Out);
1672 if (AI->hasName()) {
1673 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001674 nl(Out);
1675 }
1676 }
1677 }
1678
Chris Lattner7e6d7452010-06-21 23:12:56 +00001679 // Create all the basic blocks
1680 nl(Out);
1681 for (Function::const_iterator BI = F->begin(), BE = F->end();
1682 BI != BE; ++BI) {
1683 std::string bbname(getCppName(BI));
1684 Out << "BasicBlock* " << bbname <<
1685 " = BasicBlock::Create(mod->getContext(), \"";
1686 if (BI->hasName())
1687 printEscapedString(BI->getName());
1688 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1689 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001690 }
1691
Chris Lattner7e6d7452010-06-21 23:12:56 +00001692 // Output all of its basic blocks... for the function
1693 for (Function::const_iterator BI = F->begin(), BE = F->end();
1694 BI != BE; ++BI) {
1695 std::string bbname(getCppName(BI));
1696 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001697 nl(Out);
1698
Chris Lattner7e6d7452010-06-21 23:12:56 +00001699 // Output all of the instructions in the basic block...
1700 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1701 I != E; ++I) {
1702 printInstruction(I,bbname);
1703 }
1704 }
1705
1706 // Loop over the ForwardRefs and resolve them now that all instructions
1707 // are generated.
1708 if (!ForwardRefs.empty()) {
1709 nl(Out) << "// Resolve Forward References";
1710 nl(Out);
1711 }
1712
1713 while (!ForwardRefs.empty()) {
1714 ForwardRefMap::iterator I = ForwardRefs.begin();
1715 Out << I->second << "->replaceAllUsesWith("
1716 << getCppName(I->first) << "); delete " << I->second << ";";
1717 nl(Out);
1718 ForwardRefs.erase(I);
1719 }
1720}
1721
1722void CppWriter::printInline(const std::string& fname,
1723 const std::string& func) {
1724 const Function* F = TheModule->getFunction(func);
1725 if (!F) {
1726 error(std::string("Function '") + func + "' not found in input module");
1727 return;
1728 }
1729 if (F->isDeclaration()) {
1730 error(std::string("Function '") + func + "' is external!");
1731 return;
1732 }
1733 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1734 << getCppName(F);
1735 unsigned arg_count = 1;
1736 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1737 AI != AE; ++AI) {
1738 Out << ", Value* arg_" << arg_count;
1739 }
1740 Out << ") {";
1741 nl(Out);
1742 is_inline = true;
1743 printFunctionUses(F);
1744 printFunctionBody(F);
1745 is_inline = false;
1746 Out << "return " << getCppName(F->begin()) << ";";
1747 nl(Out) << "}";
1748 nl(Out);
1749}
1750
1751void CppWriter::printModuleBody() {
1752 // Print out all the type definitions
1753 nl(Out) << "// Type Definitions"; nl(Out);
1754 printTypes(TheModule);
1755
1756 // Functions can call each other and global variables can reference them so
1757 // define all the functions first before emitting their function bodies.
1758 nl(Out) << "// Function Declarations"; nl(Out);
1759 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1760 I != E; ++I)
1761 printFunctionHead(I);
1762
1763 // Process the global variables declarations. We can't initialze them until
1764 // after the constants are printed so just print a header for each global
1765 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1766 for (Module::const_global_iterator I = TheModule->global_begin(),
1767 E = TheModule->global_end(); I != E; ++I) {
1768 printVariableHead(I);
1769 }
1770
1771 // Print out all the constants definitions. Constants don't recurse except
1772 // through GlobalValues. All GlobalValues have been declared at this point
1773 // so we can proceed to generate the constants.
1774 nl(Out) << "// Constant Definitions"; nl(Out);
1775 printConstants(TheModule);
1776
1777 // Process the global variables definitions now that all the constants have
1778 // been emitted. These definitions just couple the gvars with their constant
1779 // initializers.
1780 nl(Out) << "// Global Variable Definitions"; nl(Out);
1781 for (Module::const_global_iterator I = TheModule->global_begin(),
1782 E = TheModule->global_end(); I != E; ++I) {
1783 printVariableBody(I);
1784 }
1785
1786 // Finally, we can safely put out all of the function bodies.
1787 nl(Out) << "// Function Definitions"; nl(Out);
1788 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1789 I != E; ++I) {
1790 if (!I->isDeclaration()) {
1791 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1792 << ")";
1793 nl(Out) << "{";
1794 nl(Out,1);
1795 printFunctionBody(I);
1796 nl(Out,-1) << "}";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001797 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001798 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001799 }
1800}
1801
1802void CppWriter::printProgram(const std::string& fname,
1803 const std::string& mName) {
1804 Out << "#include <llvm/LLVMContext.h>\n";
1805 Out << "#include <llvm/Module.h>\n";
1806 Out << "#include <llvm/DerivedTypes.h>\n";
1807 Out << "#include <llvm/Constants.h>\n";
1808 Out << "#include <llvm/GlobalVariable.h>\n";
1809 Out << "#include <llvm/Function.h>\n";
1810 Out << "#include <llvm/CallingConv.h>\n";
1811 Out << "#include <llvm/BasicBlock.h>\n";
1812 Out << "#include <llvm/Instructions.h>\n";
1813 Out << "#include <llvm/InlineAsm.h>\n";
1814 Out << "#include <llvm/Support/FormattedStream.h>\n";
1815 Out << "#include <llvm/Support/MathExtras.h>\n";
1816 Out << "#include <llvm/Pass.h>\n";
1817 Out << "#include <llvm/PassManager.h>\n";
1818 Out << "#include <llvm/ADT/SmallVector.h>\n";
1819 Out << "#include <llvm/Analysis/Verifier.h>\n";
1820 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1821 Out << "#include <algorithm>\n";
1822 Out << "using namespace llvm;\n\n";
1823 Out << "Module* " << fname << "();\n\n";
1824 Out << "int main(int argc, char**argv) {\n";
1825 Out << " Module* Mod = " << fname << "();\n";
1826 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1827 Out << " PassManager PM;\n";
1828 Out << " PM.add(createPrintModulePass(&outs()));\n";
1829 Out << " PM.run(*Mod);\n";
1830 Out << " return 0;\n";
1831 Out << "}\n\n";
1832 printModule(fname,mName);
1833}
1834
1835void CppWriter::printModule(const std::string& fname,
1836 const std::string& mName) {
1837 nl(Out) << "Module* " << fname << "() {";
1838 nl(Out,1) << "// Module Construction";
1839 nl(Out) << "Module* mod = new Module(\"";
1840 printEscapedString(mName);
1841 Out << "\", getGlobalContext());";
1842 if (!TheModule->getTargetTriple().empty()) {
1843 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1844 }
1845 if (!TheModule->getTargetTriple().empty()) {
1846 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1847 << "\");";
1848 }
1849
1850 if (!TheModule->getModuleInlineAsm().empty()) {
1851 nl(Out) << "mod->setModuleInlineAsm(\"";
1852 printEscapedString(TheModule->getModuleInlineAsm());
1853 Out << "\");";
1854 }
1855 nl(Out);
1856
1857 // Loop over the dependent libraries and emit them.
1858 Module::lib_iterator LI = TheModule->lib_begin();
1859 Module::lib_iterator LE = TheModule->lib_end();
1860 while (LI != LE) {
1861 Out << "mod->addLibrary(\"" << *LI << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001862 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001863 ++LI;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001864 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001865 printModuleBody();
1866 nl(Out) << "return mod;";
1867 nl(Out,-1) << "}";
1868 nl(Out);
1869}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001870
Chris Lattner7e6d7452010-06-21 23:12:56 +00001871void CppWriter::printContents(const std::string& fname,
1872 const std::string& mName) {
1873 Out << "\nModule* " << fname << "(Module *mod) {\n";
1874 Out << "\nmod->setModuleIdentifier(\"";
1875 printEscapedString(mName);
1876 Out << "\");\n";
1877 printModuleBody();
1878 Out << "\nreturn mod;\n";
1879 Out << "\n}\n";
1880}
1881
1882void CppWriter::printFunction(const std::string& fname,
1883 const std::string& funcName) {
1884 const Function* F = TheModule->getFunction(funcName);
1885 if (!F) {
1886 error(std::string("Function '") + funcName + "' not found in input module");
1887 return;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001888 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001889 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1890 printFunctionUses(F);
1891 printFunctionHead(F);
1892 printFunctionBody(F);
1893 Out << "return " << getCppName(F) << ";\n";
1894 Out << "}\n";
1895}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001896
Chris Lattner7e6d7452010-06-21 23:12:56 +00001897void CppWriter::printFunctions() {
1898 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1899 Module::const_iterator I = funcs.begin();
1900 Module::const_iterator IE = funcs.end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001901
Chris Lattner7e6d7452010-06-21 23:12:56 +00001902 for (; I != IE; ++I) {
1903 const Function &func = *I;
1904 if (!func.isDeclaration()) {
1905 std::string name("define_");
1906 name += func.getName();
1907 printFunction(name, func.getName());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001908 }
1909 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001910}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001911
Chris Lattner7e6d7452010-06-21 23:12:56 +00001912void CppWriter::printVariable(const std::string& fname,
1913 const std::string& varName) {
1914 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001915
Chris Lattner7e6d7452010-06-21 23:12:56 +00001916 if (!GV) {
1917 error(std::string("Variable '") + varName + "' not found in input module");
1918 return;
1919 }
1920 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1921 printVariableUses(GV);
1922 printVariableHead(GV);
1923 printVariableBody(GV);
1924 Out << "return " << getCppName(GV) << ";\n";
1925 Out << "}\n";
1926}
1927
Chris Lattner1afcace2011-07-09 17:41:24 +00001928void CppWriter::printType(const std::string &fname,
1929 const std::string &typeName) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001930 const Type* Ty = TheModule->getTypeByName(typeName);
1931 if (!Ty) {
1932 error(std::string("Type '") + typeName + "' not found in input module");
1933 return;
1934 }
1935 Out << "\nType* " << fname << "(Module *mod) {\n";
1936 printType(Ty);
1937 Out << "return " << getCppName(Ty) << ";\n";
1938 Out << "}\n";
1939}
1940
1941bool CppWriter::runOnModule(Module &M) {
1942 TheModule = &M;
1943
1944 // Emit a header
1945 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1946
1947 // Get the name of the function we're supposed to generate
1948 std::string fname = FuncName.getValue();
1949
1950 // Get the name of the thing we are to generate
1951 std::string tgtname = NameToGenerate.getValue();
1952 if (GenerationType == GenModule ||
1953 GenerationType == GenContents ||
1954 GenerationType == GenProgram ||
1955 GenerationType == GenFunctions) {
1956 if (tgtname == "!bad!") {
1957 if (M.getModuleIdentifier() == "-")
1958 tgtname = "<stdin>";
1959 else
1960 tgtname = M.getModuleIdentifier();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001961 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001962 } else if (tgtname == "!bad!")
1963 error("You must use the -for option with -gen-{function,variable,type}");
1964
1965 switch (WhatToGenerate(GenerationType)) {
1966 case GenProgram:
1967 if (fname.empty())
1968 fname = "makeLLVMModule";
1969 printProgram(fname,tgtname);
1970 break;
1971 case GenModule:
1972 if (fname.empty())
1973 fname = "makeLLVMModule";
1974 printModule(fname,tgtname);
1975 break;
1976 case GenContents:
1977 if (fname.empty())
1978 fname = "makeLLVMModuleContents";
1979 printContents(fname,tgtname);
1980 break;
1981 case GenFunction:
1982 if (fname.empty())
1983 fname = "makeLLVMFunction";
1984 printFunction(fname,tgtname);
1985 break;
1986 case GenFunctions:
1987 printFunctions();
1988 break;
1989 case GenInline:
1990 if (fname.empty())
1991 fname = "makeLLVMInline";
1992 printInline(fname,tgtname);
1993 break;
1994 case GenVariable:
1995 if (fname.empty())
1996 fname = "makeLLVMVariable";
1997 printVariable(fname,tgtname);
1998 break;
1999 case GenType:
2000 if (fname.empty())
2001 fname = "makeLLVMType";
2002 printType(fname,tgtname);
2003 break;
2004 default:
2005 error("Invalid generation option");
Anton Korobeynikov50276522008-04-23 22:29:24 +00002006 }
2007
Chris Lattner7e6d7452010-06-21 23:12:56 +00002008 return false;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002009}
2010
2011char CppWriter::ID = 0;
2012
2013//===----------------------------------------------------------------------===//
2014// External Interface declaration
2015//===----------------------------------------------------------------------===//
2016
Dan Gohman99dca4f2010-05-11 19:57:55 +00002017bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2018 formatted_raw_ostream &o,
2019 CodeGenFileType FileType,
2020 CodeGenOpt::Level OptLevel,
2021 bool DisableVerify) {
Chris Lattner211edae2010-02-02 21:06:45 +00002022 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002023 PM.add(new CppWriter(o));
2024 return false;
2025}