blob: 44394de383ff53e21ed327e35cfa327a3f395721 [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 Cheng1abf2cb2011-07-14 23:50:31 +000025#include "llvm/MC/MCAsmInfo.h"
Evan Cheng59ee62d2011-07-11 03:57:24 +000026#include "llvm/MC/MCInstrInfo.h"
Evan Chengffc0e732011-07-09 05:47:46 +000027#include "llvm/MC/MCSubtargetInfo.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000028#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/Support/CommandLine.h"
Torok Edwin30464702009-07-08 20:55:50 +000030#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000031#include "llvm/Support/FormattedStream.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000032#include "llvm/Support/TargetRegistry.h"
Chris Lattner23132b12009-08-24 03:52:50 +000033#include "llvm/ADT/StringExtras.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000034#include "llvm/Config/config.h"
35#include <algorithm>
Anton Korobeynikov50276522008-04-23 22:29:24 +000036#include <set>
Chris Lattner1afcace2011-07-09 17:41:24 +000037#include <map>
Anton Korobeynikov50276522008-04-23 22:29:24 +000038using namespace llvm;
39
40static cl::opt<std::string>
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000041FuncName("cppfname", cl::desc("Specify the name of the generated function"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000042 cl::value_desc("function name"));
43
44enum WhatToGenerate {
45 GenProgram,
46 GenModule,
47 GenContents,
48 GenFunction,
49 GenFunctions,
50 GenInline,
51 GenVariable,
52 GenType
53};
54
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000055static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000056 cl::desc("Choose what kind of output to generate"),
57 cl::init(GenProgram),
58 cl::values(
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000059 clEnumValN(GenProgram, "program", "Generate a complete program"),
60 clEnumValN(GenModule, "module", "Generate a module definition"),
61 clEnumValN(GenContents, "contents", "Generate contents of a module"),
62 clEnumValN(GenFunction, "function", "Generate a function definition"),
63 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
64 clEnumValN(GenInline, "inline", "Generate an inline function"),
65 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
66 clEnumValN(GenType, "type", "Generate a type definition"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000067 clEnumValEnd
68 )
69);
70
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000071static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000072 cl::desc("Specify the name of the thing to generate"),
73 cl::init("!bad!"));
74
Daniel Dunbar0c795d62009-07-25 06:49:55 +000075extern "C" void LLVMInitializeCppBackendTarget() {
76 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000077 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000078}
Douglas Gregor1555a232009-06-16 20:12:29 +000079
Dan Gohman844731a2008-05-13 00:00:25 +000080namespace {
Chris Lattnerdb125cf2011-07-18 04:54:35 +000081 typedef std::vector<Type*> TypeList;
82 typedef std::map<Type*,std::string> TypeMap;
Anton Korobeynikov50276522008-04-23 22:29:24 +000083 typedef std::map<const Value*,std::string> ValueMap;
84 typedef std::set<std::string> NameSet;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000085 typedef std::set<Type*> TypeSet;
Anton Korobeynikov50276522008-04-23 22:29:24 +000086 typedef std::set<const Value*> ValueSet;
87 typedef std::map<const Value*,std::string> ForwardRefMap;
88
89 /// CppWriter - This class is the main chunk of code that converts an LLVM
90 /// module to a C++ translation unit.
91 class CppWriter : public ModulePass {
David Greene71847812009-07-14 20:18:05 +000092 formatted_raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +000093 const Module *TheModule;
94 uint64_t uniqueNum;
95 TypeMap TypeNames;
96 ValueMap ValueNames;
Anton Korobeynikov50276522008-04-23 22:29:24 +000097 NameSet UsedNames;
98 TypeSet DefinedTypes;
99 ValueSet DefinedValues;
100 ForwardRefMap ForwardRefs;
101 bool is_inline;
Chris Lattner1018c242010-06-21 23:14:47 +0000102 unsigned indent_level;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000103
104 public:
105 static char ID;
David Greene71847812009-07-14 20:18:05 +0000106 explicit CppWriter(formatted_raw_ostream &o) :
Owen Anderson90c579d2010-08-06 18:33:48 +0000107 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000108
109 virtual const char *getPassName() const { return "C++ backend"; }
110
111 bool runOnModule(Module &M);
112
Anton Korobeynikov50276522008-04-23 22:29:24 +0000113 void printProgram(const std::string& fname, const std::string& modName );
114 void printModule(const std::string& fname, const std::string& modName );
115 void printContents(const std::string& fname, const std::string& modName );
116 void printFunction(const std::string& fname, const std::string& funcName );
117 void printFunctions();
118 void printInline(const std::string& fname, const std::string& funcName );
119 void printVariable(const std::string& fname, const std::string& varName );
120 void printType(const std::string& fname, const std::string& typeName );
121
122 void error(const std::string& msg);
123
Chris Lattner1018c242010-06-21 23:14:47 +0000124
125 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
126 inline void in() { indent_level++; }
127 inline void out() { if (indent_level >0) indent_level--; }
128
Anton Korobeynikov50276522008-04-23 22:29:24 +0000129 private:
130 void printLinkageType(GlobalValue::LinkageTypes LT);
131 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000132 void printCallingConv(CallingConv::ID cc);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000133 void printEscapedString(const std::string& str);
134 void printCFP(const ConstantFP* CFP);
135
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000136 std::string getCppName(Type* val);
137 inline void printCppName(Type* val);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000138
139 std::string getCppName(const Value* val);
140 inline void printCppName(const Value* val);
141
Devang Patel05988662008-09-25 21:00:45 +0000142 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000143 void printType(Type* Ty);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000144 void printTypes(const Module* M);
145
146 void printConstant(const Constant *CPV);
147 void printConstants(const Module* M);
148
149 void printVariableUses(const GlobalVariable *GV);
150 void printVariableHead(const GlobalVariable *GV);
151 void printVariableBody(const GlobalVariable *GV);
152
153 void printFunctionUses(const Function *F);
154 void printFunctionHead(const Function *F);
155 void printFunctionBody(const Function *F);
156 void printInstruction(const Instruction *I, const std::string& bbname);
Eli Friedmanbb5a7442011-09-29 20:21:17 +0000157 std::string getOpName(const Value*);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000158
159 void printModuleBody();
160 };
Chris Lattner7e6d7452010-06-21 23:12:56 +0000161} // end anonymous namespace.
Anton Korobeynikov50276522008-04-23 22:29:24 +0000162
Chris Lattner1018c242010-06-21 23:14:47 +0000163formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
164 Out << '\n';
Chris Lattner7e6d7452010-06-21 23:12:56 +0000165 if (delta >= 0 || indent_level >= unsigned(-delta))
166 indent_level += delta;
Chris Lattner1018c242010-06-21 23:14:47 +0000167 Out.indent(indent_level);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000168 return Out;
169}
170
Chris Lattner7e6d7452010-06-21 23:12:56 +0000171static inline void sanitize(std::string &str) {
172 for (size_t i = 0; i < str.length(); ++i)
173 if (!isalnum(str[i]) && str[i] != '_')
174 str[i] = '_';
175}
176
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000177static std::string getTypePrefix(Type *Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000178 switch (Ty->getTypeID()) {
179 case Type::VoidTyID: return "void_";
180 case Type::IntegerTyID:
181 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
182 case Type::FloatTyID: return "float_";
183 case Type::DoubleTyID: return "double_";
184 case Type::LabelTyID: return "label_";
185 case Type::FunctionTyID: return "func_";
186 case Type::StructTyID: return "struct_";
187 case Type::ArrayTyID: return "array_";
188 case Type::PointerTyID: return "ptr_";
189 case Type::VectorTyID: return "packed_";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000190 default: return "other_";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000191 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000192 return "unknown_";
193}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000194
Chris Lattner7e6d7452010-06-21 23:12:56 +0000195void CppWriter::error(const std::string& msg) {
196 report_fatal_error(msg);
197}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000198
Chris Lattner7e6d7452010-06-21 23:12:56 +0000199// printCFP - Print a floating point constant .. very carefully :)
200// This makes sure that conversion to/from floating yields the same binary
201// result so that we don't lose precision.
202void CppWriter::printCFP(const ConstantFP *CFP) {
203 bool ignored;
204 APFloat APF = APFloat(CFP->getValueAPF()); // copy
205 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
206 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
207 Out << "ConstantFP::get(mod->getContext(), ";
208 Out << "APFloat(";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000209#if HAVE_PRINTF_A
Chris Lattner7e6d7452010-06-21 23:12:56 +0000210 char Buffer[100];
211 sprintf(Buffer, "%A", APF.convertToDouble());
212 if ((!strncmp(Buffer, "0x", 2) ||
213 !strncmp(Buffer, "-0x", 3) ||
214 !strncmp(Buffer, "+0x", 3)) &&
215 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
216 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
217 Out << "BitsToDouble(" << Buffer << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000218 else
Chris Lattner7e6d7452010-06-21 23:12:56 +0000219 Out << "BitsToFloat((float)" << Buffer << ")";
220 Out << ")";
221 } else {
222#endif
223 std::string StrVal = ftostr(CFP->getValueAPF());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000224
Chris Lattner7e6d7452010-06-21 23:12:56 +0000225 while (StrVal[0] == ' ')
226 StrVal.erase(StrVal.begin());
227
228 // Check to make sure that the stringized number is not some string like
229 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
230 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
231 ((StrVal[0] == '-' || StrVal[0] == '+') &&
232 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
233 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
234 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
235 Out << StrVal;
236 else
237 Out << StrVal << "f";
238 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
239 Out << "BitsToDouble(0x"
240 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
241 << "ULL) /* " << StrVal << " */";
242 else
243 Out << "BitsToFloat(0x"
244 << utohexstr((uint32_t)CFP->getValueAPF().
245 bitcastToAPInt().getZExtValue())
246 << "U) /* " << StrVal << " */";
247 Out << ")";
248#if HAVE_PRINTF_A
249 }
250#endif
251 Out << ")";
252}
253
254void CppWriter::printCallingConv(CallingConv::ID cc){
255 // Print the calling convention.
256 switch (cc) {
257 case CallingConv::C: Out << "CallingConv::C"; break;
258 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
259 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
260 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
261 default: Out << cc; break;
262 }
263}
264
265void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
266 switch (LT) {
267 case GlobalValue::InternalLinkage:
268 Out << "GlobalValue::InternalLinkage"; break;
269 case GlobalValue::PrivateLinkage:
270 Out << "GlobalValue::PrivateLinkage"; break;
271 case GlobalValue::LinkerPrivateLinkage:
272 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Bill Wendling5e721d72010-07-01 21:55:59 +0000273 case GlobalValue::LinkerPrivateWeakLinkage:
274 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break;
Bill Wendling55ae5152010-08-20 22:05:50 +0000275 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
276 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000277 case GlobalValue::AvailableExternallyLinkage:
278 Out << "GlobalValue::AvailableExternallyLinkage "; break;
279 case GlobalValue::LinkOnceAnyLinkage:
280 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
281 case GlobalValue::LinkOnceODRLinkage:
282 Out << "GlobalValue::LinkOnceODRLinkage "; break;
283 case GlobalValue::WeakAnyLinkage:
284 Out << "GlobalValue::WeakAnyLinkage"; break;
285 case GlobalValue::WeakODRLinkage:
286 Out << "GlobalValue::WeakODRLinkage"; break;
287 case GlobalValue::AppendingLinkage:
288 Out << "GlobalValue::AppendingLinkage"; break;
289 case GlobalValue::ExternalLinkage:
290 Out << "GlobalValue::ExternalLinkage"; break;
291 case GlobalValue::DLLImportLinkage:
292 Out << "GlobalValue::DLLImportLinkage"; break;
293 case GlobalValue::DLLExportLinkage:
294 Out << "GlobalValue::DLLExportLinkage"; break;
295 case GlobalValue::ExternalWeakLinkage:
296 Out << "GlobalValue::ExternalWeakLinkage"; break;
297 case GlobalValue::CommonLinkage:
298 Out << "GlobalValue::CommonLinkage"; break;
299 }
300}
301
302void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
303 switch (VisType) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000304 case GlobalValue::DefaultVisibility:
305 Out << "GlobalValue::DefaultVisibility";
306 break;
307 case GlobalValue::HiddenVisibility:
308 Out << "GlobalValue::HiddenVisibility";
309 break;
310 case GlobalValue::ProtectedVisibility:
311 Out << "GlobalValue::ProtectedVisibility";
312 break;
313 }
314}
315
316// printEscapedString - Print each character of the specified string, escaping
317// it if it is not printable or if it is an escape char.
318void CppWriter::printEscapedString(const std::string &Str) {
319 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
320 unsigned char C = Str[i];
321 if (isprint(C) && C != '"' && C != '\\') {
322 Out << C;
323 } else {
324 Out << "\\x"
325 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
326 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
327 }
328 }
329}
330
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000331std::string CppWriter::getCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000332 // First, handle the primitive types .. easy
333 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
334 switch (Ty->getTypeID()) {
335 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
336 case Type::IntegerTyID: {
337 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
338 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
339 }
340 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
341 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
342 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
343 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
Dale Johannesenbb811a22010-09-10 20:55:01 +0000344 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000345 default:
346 error("Invalid primitive type");
347 break;
348 }
349 // shouldn't be returned, but make it sensible
350 return "Type::getVoidTy(mod->getContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000351 }
352
Chris Lattner7e6d7452010-06-21 23:12:56 +0000353 // Now, see if we've seen the type before and return that
354 TypeMap::iterator I = TypeNames.find(Ty);
355 if (I != TypeNames.end())
356 return I->second;
357
358 // Okay, let's build a new name for this type. Start with a prefix
359 const char* prefix = 0;
360 switch (Ty->getTypeID()) {
361 case Type::FunctionTyID: prefix = "FuncTy_"; break;
362 case Type::StructTyID: prefix = "StructTy_"; break;
363 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
364 case Type::PointerTyID: prefix = "PointerTy_"; break;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000365 case Type::VectorTyID: prefix = "VectorTy_"; break;
366 default: prefix = "OtherTy_"; break; // prevent breakage
Anton Korobeynikov50276522008-04-23 22:29:24 +0000367 }
368
Chris Lattner7e6d7452010-06-21 23:12:56 +0000369 // See if the type has a name in the symboltable and build accordingly
Chris Lattner7e6d7452010-06-21 23:12:56 +0000370 std::string name;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000371 if (StructType *STy = dyn_cast<StructType>(Ty))
Chris Lattner1afcace2011-07-09 17:41:24 +0000372 if (STy->hasName())
373 name = STy->getName();
374
375 if (name.empty())
376 name = utostr(uniqueNum++);
377
378 name = std::string(prefix) + name;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000379 sanitize(name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000380
Chris Lattner7e6d7452010-06-21 23:12:56 +0000381 // Save the name
382 return TypeNames[Ty] = name;
383}
384
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000385void CppWriter::printCppName(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000386 printEscapedString(getCppName(Ty));
387}
388
389std::string CppWriter::getCppName(const Value* val) {
390 std::string name;
391 ValueMap::iterator I = ValueNames.find(val);
392 if (I != ValueNames.end() && I->first == val)
393 return I->second;
394
395 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
396 name = std::string("gvar_") +
397 getTypePrefix(GV->getType()->getElementType());
398 } else if (isa<Function>(val)) {
399 name = std::string("func_");
400 } else if (const Constant* C = dyn_cast<Constant>(val)) {
401 name = std::string("const_") + getTypePrefix(C->getType());
402 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
403 if (is_inline) {
404 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
405 Function::const_arg_iterator(Arg)) + 1;
406 name = std::string("arg_") + utostr(argNum);
407 NameSet::iterator NI = UsedNames.find(name);
408 if (NI != UsedNames.end())
409 name += std::string("_") + utostr(uniqueNum++);
410 UsedNames.insert(name);
411 return ValueNames[val] = name;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000412 } else {
413 name = getTypePrefix(val->getType());
414 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000415 } else {
416 name = getTypePrefix(val->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000417 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000418 if (val->hasName())
419 name += val->getName();
420 else
421 name += utostr(uniqueNum++);
422 sanitize(name);
423 NameSet::iterator NI = UsedNames.find(name);
424 if (NI != UsedNames.end())
425 name += std::string("_") + utostr(uniqueNum++);
426 UsedNames.insert(name);
427 return ValueNames[val] = name;
428}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000429
Chris Lattner7e6d7452010-06-21 23:12:56 +0000430void CppWriter::printCppName(const Value* val) {
431 printEscapedString(getCppName(val));
432}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000433
Chris Lattner7e6d7452010-06-21 23:12:56 +0000434void CppWriter::printAttributes(const AttrListPtr &PAL,
435 const std::string &name) {
436 Out << "AttrListPtr " << name << "_PAL;";
437 nl(Out);
438 if (!PAL.isEmpty()) {
439 Out << '{'; in(); nl(Out);
440 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
441 Out << "AttributeWithIndex PAWI;"; nl(Out);
442 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
443 unsigned index = PAL.getSlot(i).Index;
444 Attributes attrs = PAL.getSlot(i).Attrs;
445 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
Chris Lattneracca9552009-01-13 07:22:22 +0000446#define HANDLE_ATTR(X) \
Chris Lattner7e6d7452010-06-21 23:12:56 +0000447 if (attrs & Attribute::X) \
448 Out << " | Attribute::" #X; \
449 attrs &= ~Attribute::X;
450
451 HANDLE_ATTR(SExt);
452 HANDLE_ATTR(ZExt);
453 HANDLE_ATTR(NoReturn);
454 HANDLE_ATTR(InReg);
455 HANDLE_ATTR(StructRet);
456 HANDLE_ATTR(NoUnwind);
457 HANDLE_ATTR(NoAlias);
458 HANDLE_ATTR(ByVal);
459 HANDLE_ATTR(Nest);
460 HANDLE_ATTR(ReadNone);
461 HANDLE_ATTR(ReadOnly);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000462 HANDLE_ATTR(NoInline);
463 HANDLE_ATTR(AlwaysInline);
464 HANDLE_ATTR(OptimizeForSize);
465 HANDLE_ATTR(StackProtect);
466 HANDLE_ATTR(StackProtectReq);
467 HANDLE_ATTR(NoCapture);
Eli Friedman32bb4df2010-07-16 18:47:20 +0000468 HANDLE_ATTR(NoRedZone);
469 HANDLE_ATTR(NoImplicitFloat);
470 HANDLE_ATTR(Naked);
471 HANDLE_ATTR(InlineHint);
Rafael Espindola25456ef2011-10-03 14:45:37 +0000472 HANDLE_ATTR(ReturnsTwice);
Bill Wendling54f15362011-08-09 00:47:30 +0000473 HANDLE_ATTR(UWTable);
474 HANDLE_ATTR(NonLazyBind);
Chris Lattneracca9552009-01-13 07:22:22 +0000475#undef HANDLE_ATTR
Eli Friedman32bb4df2010-07-16 18:47:20 +0000476 if (attrs & Attribute::StackAlignment)
477 Out << " | Attribute::constructStackAlignmentFromInt("
478 << Attribute::getStackAlignmentFromAttrs(attrs)
479 << ")";
480 attrs &= ~Attribute::StackAlignment;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000481 assert(attrs == 0 && "Unhandled attribute!");
482 Out << ";";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000483 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000484 Out << "Attrs.push_back(PAWI);";
485 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000486 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000487 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
488 nl(Out);
489 out(); nl(Out);
490 Out << '}'; nl(Out);
491 }
492}
493
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000494void CppWriter::printType(Type* Ty) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000495 // We don't print definitions for primitive types
496 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000497 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000498
499 // If we already defined this type, we don't need to define it again.
500 if (DefinedTypes.find(Ty) != DefinedTypes.end())
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000501 return;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000502
503 // Everything below needs the name for the type so get it now.
504 std::string typeName(getCppName(Ty));
505
Chris Lattner7e6d7452010-06-21 23:12:56 +0000506 // Print the type definition
507 switch (Ty->getTypeID()) {
508 case Type::FunctionTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000509 FunctionType* FT = cast<FunctionType>(Ty);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000510 Out << "std::vector<Type*>" << typeName << "_args;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000511 nl(Out);
512 FunctionType::param_iterator PI = FT->param_begin();
513 FunctionType::param_iterator PE = FT->param_end();
514 for (; PI != PE; ++PI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000515 Type* argTy = static_cast<Type*>(*PI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000516 printType(argTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000517 std::string argName(getCppName(argTy));
518 Out << typeName << "_args.push_back(" << argName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000519 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000520 nl(Out);
521 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000522 printType(FT->getReturnType());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000523 std::string retTypeName(getCppName(FT->getReturnType()));
524 Out << "FunctionType* " << typeName << " = FunctionType::get(";
525 in(); nl(Out) << "/*Result=*/" << retTypeName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000526 Out << ",";
527 nl(Out) << "/*Params=*/" << typeName << "_args,";
528 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
529 out();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000530 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000531 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000532 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000533 case Type::StructTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000534 StructType* ST = cast<StructType>(Ty);
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000535 if (!ST->isLiteral()) {
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000536 Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
537 printEscapedString(ST->getName());
538 Out << "\");";
539 nl(Out);
540 Out << "if (!" << typeName << ") {";
541 nl(Out);
542 Out << typeName << " = ";
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000543 Out << "StructType::create(mod->getContext(), \"";
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000544 printEscapedString(ST->getName());
545 Out << "\");";
546 nl(Out);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000547 Out << "}";
548 nl(Out);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000549 // Indicate that this type is now defined.
550 DefinedTypes.insert(Ty);
551 }
552
553 Out << "std::vector<Type*>" << typeName << "_fields;";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000554 nl(Out);
555 StructType::element_iterator EI = ST->element_begin();
556 StructType::element_iterator EE = ST->element_end();
557 for (; EI != EE; ++EI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000558 Type* fieldTy = static_cast<Type*>(*EI);
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000559 printType(fieldTy);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000560 std::string fieldName(getCppName(fieldTy));
561 Out << typeName << "_fields.push_back(" << fieldName;
Chris Lattner7e6d7452010-06-21 23:12:56 +0000562 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000563 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000564 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000565
Chris Lattnerc4d0e9f2011-08-12 18:07:07 +0000566 if (ST->isLiteral()) {
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000567 Out << "StructType *" << typeName << " = ";
Chris Lattner1afcace2011-07-09 17:41:24 +0000568 Out << "StructType::get(" << "mod->getContext(), ";
569 } else {
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000570 Out << "if (" << typeName << "->isOpaque()) {";
571 nl(Out);
Chris Lattner1afcace2011-07-09 17:41:24 +0000572 Out << typeName << "->setBody(";
573 }
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000574
Chris Lattner1afcace2011-07-09 17:41:24 +0000575 Out << typeName << "_fields, /*isPacked=*/"
Chris Lattner7e6d7452010-06-21 23:12:56 +0000576 << (ST->isPacked() ? "true" : "false") << ");";
577 nl(Out);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +0000578 if (!ST->isLiteral()) {
579 Out << "}";
580 nl(Out);
581 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000582 break;
583 }
584 case Type::ArrayTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000585 ArrayType* AT = cast<ArrayType>(Ty);
586 Type* ET = AT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000587 printType(ET);
588 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
589 std::string elemName(getCppName(ET));
590 Out << "ArrayType* " << typeName << " = ArrayType::get("
591 << elemName
592 << ", " << utostr(AT->getNumElements()) << ");";
593 nl(Out);
594 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000595 break;
596 }
597 case Type::PointerTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000598 PointerType* PT = cast<PointerType>(Ty);
599 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000600 printType(ET);
601 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
602 std::string elemName(getCppName(ET));
603 Out << "PointerType* " << typeName << " = PointerType::get("
604 << elemName
605 << ", " << utostr(PT->getAddressSpace()) << ");";
606 nl(Out);
607 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000608 break;
609 }
610 case Type::VectorTyID: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000611 VectorType* PT = cast<VectorType>(Ty);
612 Type* ET = PT->getElementType();
Nicolas Geoffray5cf9fcd2011-07-14 21:04:35 +0000613 printType(ET);
614 if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
615 std::string elemName(getCppName(ET));
616 Out << "VectorType* " << typeName << " = VectorType::get("
617 << elemName
618 << ", " << utostr(PT->getNumElements()) << ");";
619 nl(Out);
620 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000621 break;
622 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000623 default:
624 error("Invalid TypeID");
625 }
626
Chris Lattner7e6d7452010-06-21 23:12:56 +0000627 // Indicate that this type is now defined.
628 DefinedTypes.insert(Ty);
629
Chris Lattner7e6d7452010-06-21 23:12:56 +0000630 // Finally, separate the type definition from other with a newline.
631 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000632}
633
634void CppWriter::printTypes(const Module* M) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000635 // Add all of the global variables to the value table.
Chris Lattner7e6d7452010-06-21 23:12:56 +0000636 for (Module::const_global_iterator I = TheModule->global_begin(),
637 E = TheModule->global_end(); I != E; ++I) {
638 if (I->hasInitializer())
639 printType(I->getInitializer()->getType());
640 printType(I->getType());
641 }
642
643 // Add all the functions to the table
644 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
645 FI != FE; ++FI) {
646 printType(FI->getReturnType());
647 printType(FI->getFunctionType());
648 // Add all the function arguments
649 for (Function::const_arg_iterator AI = FI->arg_begin(),
650 AE = FI->arg_end(); AI != AE; ++AI) {
651 printType(AI->getType());
652 }
653
654 // Add all of the basic blocks and instructions
655 for (Function::const_iterator BB = FI->begin(),
656 E = FI->end(); BB != E; ++BB) {
657 printType(BB->getType());
658 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
659 ++I) {
660 printType(I->getType());
661 for (unsigned i = 0; i < I->getNumOperands(); ++i)
662 printType(I->getOperand(i)->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000663 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000664 }
665 }
666}
667
668
669// printConstant - Print out a constant pool entry...
670void CppWriter::printConstant(const Constant *CV) {
671 // First, if the constant is actually a GlobalValue (variable or function)
672 // or its already in the constant list then we've printed it already and we
673 // can just return.
674 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
675 return;
676
677 std::string constName(getCppName(CV));
678 std::string typeName(getCppName(CV->getType()));
679
680 if (isa<GlobalValue>(CV)) {
681 // Skip variables and functions, we emit them elsewhere
682 return;
683 }
684
685 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
686 std::string constValue = CI->getValue().toString(10, true);
687 Out << "ConstantInt* " << constName
688 << " = ConstantInt::get(mod->getContext(), APInt("
689 << cast<IntegerType>(CI->getType())->getBitWidth()
690 << ", StringRef(\"" << constValue << "\"), 10));";
691 } else if (isa<ConstantAggregateZero>(CV)) {
692 Out << "ConstantAggregateZero* " << constName
693 << " = ConstantAggregateZero::get(" << typeName << ");";
694 } else if (isa<ConstantPointerNull>(CV)) {
695 Out << "ConstantPointerNull* " << constName
696 << " = ConstantPointerNull::get(" << typeName << ");";
697 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
698 Out << "ConstantFP* " << constName << " = ";
699 printCFP(CFP);
700 Out << ";";
701 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
702 if (CA->isString() &&
703 CA->getType()->getElementType() ==
704 Type::getInt8Ty(CA->getContext())) {
705 Out << "Constant* " << constName <<
706 " = ConstantArray::get(mod->getContext(), \"";
707 std::string tmp = CA->getAsString();
708 bool nullTerminate = false;
709 if (tmp[tmp.length()-1] == 0) {
710 tmp.erase(tmp.length()-1);
711 nullTerminate = true;
712 }
713 printEscapedString(tmp);
714 // Determine if we want null termination or not.
715 if (nullTerminate)
716 Out << "\", true"; // Indicate that the null terminator should be
717 // added.
718 else
719 Out << "\", false";// No null terminator
720 Out << ");";
721 } else {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000722 Out << "std::vector<Constant*> " << constName << "_elems;";
723 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000724 unsigned N = CA->getNumOperands();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000725 for (unsigned i = 0; i < N; ++i) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000726 printConstant(CA->getOperand(i)); // recurse to print operands
Anton Korobeynikov50276522008-04-23 22:29:24 +0000727 Out << constName << "_elems.push_back("
Chris Lattner7e6d7452010-06-21 23:12:56 +0000728 << getCppName(CA->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000729 nl(Out);
730 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000731 Out << "Constant* " << constName << " = ConstantArray::get("
Anton Korobeynikov50276522008-04-23 22:29:24 +0000732 << typeName << ", " << constName << "_elems);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000733 }
734 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
735 Out << "std::vector<Constant*> " << constName << "_fields;";
736 nl(Out);
737 unsigned N = CS->getNumOperands();
738 for (unsigned i = 0; i < N; i++) {
739 printConstant(CS->getOperand(i));
740 Out << constName << "_fields.push_back("
741 << getCppName(CS->getOperand(i)) << ");";
742 nl(Out);
743 }
744 Out << "Constant* " << constName << " = ConstantStruct::get("
745 << typeName << ", " << constName << "_fields);";
746 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
747 Out << "std::vector<Constant*> " << constName << "_elems;";
748 nl(Out);
749 unsigned N = CP->getNumOperands();
750 for (unsigned i = 0; i < N; ++i) {
751 printConstant(CP->getOperand(i));
752 Out << constName << "_elems.push_back("
753 << getCppName(CP->getOperand(i)) << ");";
754 nl(Out);
755 }
756 Out << "Constant* " << constName << " = ConstantVector::get("
757 << typeName << ", " << constName << "_elems);";
758 } else if (isa<UndefValue>(CV)) {
759 Out << "UndefValue* " << constName << " = UndefValue::get("
760 << typeName << ");";
761 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
762 if (CE->getOpcode() == Instruction::GetElementPtr) {
763 Out << "std::vector<Constant*> " << constName << "_indices;";
764 nl(Out);
765 printConstant(CE->getOperand(0));
766 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
767 printConstant(CE->getOperand(i));
768 Out << constName << "_indices.push_back("
769 << getCppName(CE->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000770 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000771 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000772 Out << "Constant* " << constName
773 << " = ConstantExpr::getGetElementPtr("
774 << getCppName(CE->getOperand(0)) << ", "
Nicolas Geoffraya056d202011-07-21 20:59:21 +0000775 << constName << "_indices);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000776 } else if (CE->isCast()) {
777 printConstant(CE->getOperand(0));
778 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
779 switch (CE->getOpcode()) {
780 default: llvm_unreachable("Invalid cast opcode");
781 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
782 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
783 case Instruction::SExt: Out << "Instruction::SExt"; break;
784 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
785 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
786 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
787 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
788 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
789 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
790 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
791 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
792 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
793 }
794 Out << ", " << getCppName(CE->getOperand(0)) << ", "
795 << getCppName(CE->getType()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000796 } else {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000797 unsigned N = CE->getNumOperands();
798 for (unsigned i = 0; i < N; ++i ) {
799 printConstant(CE->getOperand(i));
800 }
801 Out << "Constant* " << constName << " = ConstantExpr::";
802 switch (CE->getOpcode()) {
803 case Instruction::Add: Out << "getAdd("; break;
804 case Instruction::FAdd: Out << "getFAdd("; break;
805 case Instruction::Sub: Out << "getSub("; break;
806 case Instruction::FSub: Out << "getFSub("; break;
807 case Instruction::Mul: Out << "getMul("; break;
808 case Instruction::FMul: Out << "getFMul("; break;
809 case Instruction::UDiv: Out << "getUDiv("; break;
810 case Instruction::SDiv: Out << "getSDiv("; break;
811 case Instruction::FDiv: Out << "getFDiv("; break;
812 case Instruction::URem: Out << "getURem("; break;
813 case Instruction::SRem: Out << "getSRem("; break;
814 case Instruction::FRem: Out << "getFRem("; break;
815 case Instruction::And: Out << "getAnd("; break;
816 case Instruction::Or: Out << "getOr("; break;
817 case Instruction::Xor: Out << "getXor("; break;
818 case Instruction::ICmp:
819 Out << "getICmp(ICmpInst::ICMP_";
820 switch (CE->getPredicate()) {
821 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
822 case ICmpInst::ICMP_NE: Out << "NE"; break;
823 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
824 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
825 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
826 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
827 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
828 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
829 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
830 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
831 default: error("Invalid ICmp Predicate");
832 }
833 break;
834 case Instruction::FCmp:
835 Out << "getFCmp(FCmpInst::FCMP_";
836 switch (CE->getPredicate()) {
837 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
838 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
839 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
840 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
841 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
842 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
843 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
844 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
845 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
846 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
847 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
848 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
849 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
850 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
851 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
852 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
853 default: error("Invalid FCmp Predicate");
854 }
855 break;
856 case Instruction::Shl: Out << "getShl("; break;
857 case Instruction::LShr: Out << "getLShr("; break;
858 case Instruction::AShr: Out << "getAShr("; break;
859 case Instruction::Select: Out << "getSelect("; break;
860 case Instruction::ExtractElement: Out << "getExtractElement("; break;
861 case Instruction::InsertElement: Out << "getInsertElement("; break;
862 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
863 default:
864 error("Invalid constant expression");
865 break;
866 }
867 Out << getCppName(CE->getOperand(0));
868 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
869 Out << ", " << getCppName(CE->getOperand(i));
870 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000871 }
Chris Lattner32848772010-06-21 23:19:36 +0000872 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
873 Out << "Constant* " << constName << " = ";
874 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000875 } else {
876 error("Bad Constant");
877 Out << "Constant* " << constName << " = 0; ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000878 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000879 nl(Out);
880}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000881
Chris Lattner7e6d7452010-06-21 23:12:56 +0000882void CppWriter::printConstants(const Module* M) {
883 // Traverse all the global variables looking for constant initializers
884 for (Module::const_global_iterator I = TheModule->global_begin(),
885 E = TheModule->global_end(); I != E; ++I)
886 if (I->hasInitializer())
887 printConstant(I->getInitializer());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000888
Chris Lattner7e6d7452010-06-21 23:12:56 +0000889 // Traverse the LLVM functions looking for constants
890 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
891 FI != FE; ++FI) {
892 // Add all of the basic blocks and instructions
893 for (Function::const_iterator BB = FI->begin(),
894 E = FI->end(); BB != E; ++BB) {
895 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
896 ++I) {
897 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
898 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
899 printConstant(C);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000900 }
901 }
902 }
903 }
904 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000905}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000906
Chris Lattner7e6d7452010-06-21 23:12:56 +0000907void CppWriter::printVariableUses(const GlobalVariable *GV) {
908 nl(Out) << "// Type Definitions";
909 nl(Out);
910 printType(GV->getType());
911 if (GV->hasInitializer()) {
Jay Foad7d715df2011-06-19 18:37:11 +0000912 const Constant *Init = GV->getInitializer();
Chris Lattner7e6d7452010-06-21 23:12:56 +0000913 printType(Init->getType());
Jay Foad7d715df2011-06-19 18:37:11 +0000914 if (const Function *F = dyn_cast<Function>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000915 nl(Out)<< "/ Function Declarations"; nl(Out);
916 printFunctionHead(F);
Jay Foad7d715df2011-06-19 18:37:11 +0000917 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000918 nl(Out) << "// Global Variable Declarations"; nl(Out);
919 printVariableHead(gv);
920
921 nl(Out) << "// Global Variable Definitions"; nl(Out);
922 printVariableBody(gv);
923 } else {
924 nl(Out) << "// Constant Definitions"; nl(Out);
925 printConstant(Init);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000926 }
927 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000928}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000929
Chris Lattner7e6d7452010-06-21 23:12:56 +0000930void CppWriter::printVariableHead(const GlobalVariable *GV) {
931 nl(Out) << "GlobalVariable* " << getCppName(GV);
932 if (is_inline) {
933 Out << " = mod->getGlobalVariable(mod->getContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000934 printEscapedString(GV->getName());
Chris Lattner7e6d7452010-06-21 23:12:56 +0000935 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
936 nl(Out) << "if (!" << getCppName(GV) << ") {";
937 in(); nl(Out) << getCppName(GV);
938 }
939 Out << " = new GlobalVariable(/*Module=*/*mod, ";
940 nl(Out) << "/*Type=*/";
941 printCppName(GV->getType()->getElementType());
942 Out << ",";
943 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
944 Out << ",";
945 nl(Out) << "/*Linkage=*/";
946 printLinkageType(GV->getLinkage());
947 Out << ",";
948 nl(Out) << "/*Initializer=*/0, ";
949 if (GV->hasInitializer()) {
950 Out << "// has initializer, specified below";
951 }
952 nl(Out) << "/*Name=*/\"";
953 printEscapedString(GV->getName());
954 Out << "\");";
955 nl(Out);
956
957 if (GV->hasSection()) {
958 printCppName(GV);
959 Out << "->setSection(\"";
960 printEscapedString(GV->getSection());
Owen Anderson16a412e2009-07-10 16:42:19 +0000961 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000962 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000963 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000964 if (GV->getAlignment()) {
965 printCppName(GV);
966 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000967 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000968 }
969 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
970 printCppName(GV);
971 Out << "->setVisibility(";
972 printVisibilityType(GV->getVisibility());
973 Out << ");";
974 nl(Out);
975 }
976 if (GV->isThreadLocal()) {
977 printCppName(GV);
978 Out << "->setThreadLocal(true);";
979 nl(Out);
980 }
981 if (is_inline) {
982 out(); Out << "}"; nl(Out);
983 }
984}
985
986void CppWriter::printVariableBody(const GlobalVariable *GV) {
987 if (GV->hasInitializer()) {
988 printCppName(GV);
989 Out << "->setInitializer(";
990 Out << getCppName(GV->getInitializer()) << ");";
991 nl(Out);
992 }
993}
994
Eli Friedmanbb5a7442011-09-29 20:21:17 +0000995std::string CppWriter::getOpName(const Value* V) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000996 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
997 return getCppName(V);
998
999 // See if its alread in the map of forward references, if so just return the
1000 // name we already set up for it
1001 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1002 if (I != ForwardRefs.end())
1003 return I->second;
1004
1005 // This is a new forward reference. Generate a unique name for it
1006 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1007
1008 // Yes, this is a hack. An Argument is the smallest instantiable value that
1009 // we can make as a placeholder for the real value. We'll replace these
1010 // Argument instances later.
1011 Out << "Argument* " << result << " = new Argument("
1012 << getCppName(V->getType()) << ");";
1013 nl(Out);
1014 ForwardRefs[V] = result;
1015 return result;
1016}
1017
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001018static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
1019 switch (Ordering) {
1020 case NotAtomic: return "NotAtomic";
1021 case Unordered: return "Unordered";
1022 case Monotonic: return "Monotonic";
1023 case Acquire: return "Acquire";
1024 case Release: return "Release";
1025 case AcquireRelease: return "AcquireRelease";
1026 case SequentiallyConsistent: return "SequentiallyConsistent";
1027 }
1028 llvm_unreachable("Unknown ordering");
1029}
1030
1031static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
1032 switch (SynchScope) {
1033 case SingleThread: return "SingleThread";
1034 case CrossThread: return "CrossThread";
1035 }
1036 llvm_unreachable("Unknown synch scope");
1037}
1038
Chris Lattner7e6d7452010-06-21 23:12:56 +00001039// printInstruction - This member is called for each Instruction in a function.
1040void CppWriter::printInstruction(const Instruction *I,
1041 const std::string& bbname) {
1042 std::string iName(getCppName(I));
1043
1044 // Before we emit this instruction, we need to take care of generating any
1045 // forward references. So, we get the names of all the operands in advance
1046 const unsigned Ops(I->getNumOperands());
1047 std::string* opNames = new std::string[Ops];
Chris Lattner32848772010-06-21 23:19:36 +00001048 for (unsigned i = 0; i < Ops; i++)
Chris Lattner7e6d7452010-06-21 23:12:56 +00001049 opNames[i] = getOpName(I->getOperand(i));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001050
Chris Lattner7e6d7452010-06-21 23:12:56 +00001051 switch (I->getOpcode()) {
1052 default:
1053 error("Invalid instruction");
1054 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001055
Chris Lattner7e6d7452010-06-21 23:12:56 +00001056 case Instruction::Ret: {
1057 const ReturnInst* ret = cast<ReturnInst>(I);
1058 Out << "ReturnInst::Create(mod->getContext(), "
1059 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1060 break;
1061 }
1062 case Instruction::Br: {
1063 const BranchInst* br = cast<BranchInst>(I);
1064 Out << "BranchInst::Create(" ;
Chris Lattner32848772010-06-21 23:19:36 +00001065 if (br->getNumOperands() == 3) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001066 Out << opNames[2] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001067 << opNames[1] << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001068 << opNames[0] << ", ";
1069
1070 } else if (br->getNumOperands() == 1) {
1071 Out << opNames[0] << ", ";
1072 } else {
1073 error("Branch with 2 operands?");
1074 }
1075 Out << bbname << ");";
1076 break;
1077 }
1078 case Instruction::Switch: {
1079 const SwitchInst *SI = cast<SwitchInst>(I);
1080 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001081 << getOpName(SI->getCondition()) << ", "
1082 << getOpName(SI->getDefaultDest()) << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001083 << SI->getNumCases() << ", " << bbname << ");";
1084 nl(Out);
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001085 unsigned NumCases = SI->getNumCases();
1086 for (unsigned i = 1; i < NumCases; ++i) {
1087 const ConstantInt* CaseVal = SI->getCaseValue(i);
1088 const BasicBlock* BB = SI->getSuccessor(i);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001089 Out << iName << "->addCase("
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001090 << getOpName(CaseVal) << ", "
1091 << getOpName(BB) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001092 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001093 }
1094 break;
1095 }
1096 case Instruction::IndirectBr: {
1097 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1098 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1099 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1100 nl(Out);
1101 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1102 Out << iName << "->addDestination(" << opNames[i] << ");";
1103 nl(Out);
1104 }
1105 break;
1106 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00001107 case Instruction::Resume: {
1108 Out << "ResumeInst::Create(mod->getContext(), " << opNames[0]
1109 << ", " << bbname << ");";
1110 break;
1111 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001112 case Instruction::Invoke: {
1113 const InvokeInst* inv = cast<InvokeInst>(I);
1114 Out << "std::vector<Value*> " << iName << "_params;";
1115 nl(Out);
1116 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1117 Out << iName << "_params.push_back("
1118 << getOpName(inv->getArgOperand(i)) << ");";
1119 nl(Out);
1120 }
1121 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1122 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1123 << getOpName(inv->getCalledFunction()) << ", "
1124 << getOpName(inv->getNormalDest()) << ", "
1125 << getOpName(inv->getUnwindDest()) << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001126 << iName << "_params, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001127 printEscapedString(inv->getName());
1128 Out << "\", " << bbname << ");";
1129 nl(Out) << iName << "->setCallingConv(";
1130 printCallingConv(inv->getCallingConv());
1131 Out << ");";
1132 printAttributes(inv->getAttributes(), iName);
1133 Out << iName << "->setAttributes(" << iName << "_PAL);";
1134 nl(Out);
1135 break;
1136 }
1137 case Instruction::Unwind: {
1138 Out << "new UnwindInst("
1139 << bbname << ");";
1140 break;
1141 }
1142 case Instruction::Unreachable: {
1143 Out << "new UnreachableInst("
1144 << "mod->getContext(), "
1145 << bbname << ");";
1146 break;
1147 }
1148 case Instruction::Add:
1149 case Instruction::FAdd:
1150 case Instruction::Sub:
1151 case Instruction::FSub:
1152 case Instruction::Mul:
1153 case Instruction::FMul:
1154 case Instruction::UDiv:
1155 case Instruction::SDiv:
1156 case Instruction::FDiv:
1157 case Instruction::URem:
1158 case Instruction::SRem:
1159 case Instruction::FRem:
1160 case Instruction::And:
1161 case Instruction::Or:
1162 case Instruction::Xor:
1163 case Instruction::Shl:
1164 case Instruction::LShr:
1165 case Instruction::AShr:{
1166 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1167 switch (I->getOpcode()) {
1168 case Instruction::Add: Out << "Instruction::Add"; break;
1169 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1170 case Instruction::Sub: Out << "Instruction::Sub"; break;
1171 case Instruction::FSub: Out << "Instruction::FSub"; break;
1172 case Instruction::Mul: Out << "Instruction::Mul"; break;
1173 case Instruction::FMul: Out << "Instruction::FMul"; break;
1174 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1175 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1176 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1177 case Instruction::URem:Out << "Instruction::URem"; break;
1178 case Instruction::SRem:Out << "Instruction::SRem"; break;
1179 case Instruction::FRem:Out << "Instruction::FRem"; break;
1180 case Instruction::And: Out << "Instruction::And"; break;
1181 case Instruction::Or: Out << "Instruction::Or"; break;
1182 case Instruction::Xor: Out << "Instruction::Xor"; break;
1183 case Instruction::Shl: Out << "Instruction::Shl"; break;
1184 case Instruction::LShr:Out << "Instruction::LShr"; break;
1185 case Instruction::AShr:Out << "Instruction::AShr"; break;
1186 default: Out << "Instruction::BadOpCode"; break;
1187 }
1188 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1189 printEscapedString(I->getName());
1190 Out << "\", " << bbname << ");";
1191 break;
1192 }
1193 case Instruction::FCmp: {
1194 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1195 switch (cast<FCmpInst>(I)->getPredicate()) {
1196 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1197 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1198 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1199 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1200 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1201 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1202 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1203 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1204 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1205 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1206 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1207 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1208 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1209 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1210 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1211 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1212 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1213 }
1214 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1215 printEscapedString(I->getName());
1216 Out << "\");";
1217 break;
1218 }
1219 case Instruction::ICmp: {
1220 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1221 switch (cast<ICmpInst>(I)->getPredicate()) {
1222 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1223 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1224 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1225 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1226 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1227 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1228 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1229 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1230 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1231 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1232 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1233 }
1234 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1235 printEscapedString(I->getName());
1236 Out << "\");";
1237 break;
1238 }
1239 case Instruction::Alloca: {
1240 const AllocaInst* allocaI = cast<AllocaInst>(I);
1241 Out << "AllocaInst* " << iName << " = new AllocaInst("
1242 << getCppName(allocaI->getAllocatedType()) << ", ";
1243 if (allocaI->isArrayAllocation())
1244 Out << opNames[0] << ", ";
1245 Out << "\"";
1246 printEscapedString(allocaI->getName());
1247 Out << "\", " << bbname << ");";
1248 if (allocaI->getAlignment())
1249 nl(Out) << iName << "->setAlignment("
1250 << allocaI->getAlignment() << ");";
1251 break;
1252 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001253 case Instruction::Load: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001254 const LoadInst* load = cast<LoadInst>(I);
1255 Out << "LoadInst* " << iName << " = new LoadInst("
1256 << opNames[0] << ", \"";
1257 printEscapedString(load->getName());
1258 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1259 << ", " << bbname << ");";
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001260 if (load->getAlignment())
1261 nl(Out) << iName << "->setAlignment("
1262 << load->getAlignment() << ");";
1263 if (load->isAtomic()) {
1264 StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1265 StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1266 nl(Out) << iName << "->setAtomic("
1267 << Ordering << ", " << CrossThread << ");";
1268 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001269 break;
1270 }
1271 case Instruction::Store: {
1272 const StoreInst* store = cast<StoreInst>(I);
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001273 Out << "StoreInst* " << iName << " = new StoreInst("
Chris Lattner7e6d7452010-06-21 23:12:56 +00001274 << opNames[0] << ", "
1275 << opNames[1] << ", "
1276 << (store->isVolatile() ? "true" : "false")
1277 << ", " << bbname << ");";
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001278 if (store->getAlignment())
1279 nl(Out) << iName << "->setAlignment("
1280 << store->getAlignment() << ");";
1281 if (store->isAtomic()) {
1282 StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1283 StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1284 nl(Out) << iName << "->setAtomic("
1285 << Ordering << ", " << CrossThread << ");";
1286 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001287 break;
1288 }
1289 case Instruction::GetElementPtr: {
1290 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1291 if (gep->getNumOperands() <= 2) {
1292 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1293 << opNames[0];
1294 if (gep->getNumOperands() == 2)
1295 Out << ", " << opNames[1];
1296 } else {
1297 Out << "std::vector<Value*> " << iName << "_indices;";
1298 nl(Out);
1299 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1300 Out << iName << "_indices.push_back("
1301 << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001302 nl(Out);
1303 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001304 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
Nicolas Geoffray45c8d2b2011-07-26 20:52:25 +00001305 << opNames[0] << ", " << iName << "_indices";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001306 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001307 Out << ", \"";
1308 printEscapedString(gep->getName());
1309 Out << "\", " << bbname << ");";
1310 break;
1311 }
1312 case Instruction::PHI: {
1313 const PHINode* phi = cast<PHINode>(I);
1314
1315 Out << "PHINode* " << iName << " = PHINode::Create("
Nicolas Geoffrayc6cf1972011-04-10 17:39:40 +00001316 << getCppName(phi->getType()) << ", "
Jay Foad3ecfc862011-03-30 11:28:46 +00001317 << phi->getNumIncomingValues() << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001318 printEscapedString(phi->getName());
1319 Out << "\", " << bbname << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001320 nl(Out);
Jay Foadc1371202011-06-20 14:18:48 +00001321 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001322 Out << iName << "->addIncoming("
Jay Foadc1371202011-06-20 14:18:48 +00001323 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
Jay Foad95c3e482011-06-23 09:09:15 +00001324 << getOpName(phi->getIncomingBlock(i)) << ");";
Chris Lattner627b4702009-10-27 21:24:48 +00001325 nl(Out);
Chris Lattner627b4702009-10-27 21:24:48 +00001326 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001327 break;
1328 }
1329 case Instruction::Trunc:
1330 case Instruction::ZExt:
1331 case Instruction::SExt:
1332 case Instruction::FPTrunc:
1333 case Instruction::FPExt:
1334 case Instruction::FPToUI:
1335 case Instruction::FPToSI:
1336 case Instruction::UIToFP:
1337 case Instruction::SIToFP:
1338 case Instruction::PtrToInt:
1339 case Instruction::IntToPtr:
1340 case Instruction::BitCast: {
1341 const CastInst* cst = cast<CastInst>(I);
1342 Out << "CastInst* " << iName << " = new ";
1343 switch (I->getOpcode()) {
1344 case Instruction::Trunc: Out << "TruncInst"; break;
1345 case Instruction::ZExt: Out << "ZExtInst"; break;
1346 case Instruction::SExt: Out << "SExtInst"; break;
1347 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1348 case Instruction::FPExt: Out << "FPExtInst"; break;
1349 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1350 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1351 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1352 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1353 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1354 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1355 case Instruction::BitCast: Out << "BitCastInst"; break;
Richard Trieu23946fc2011-09-21 03:09:09 +00001356 default: assert(0 && "Unreachable"); break;
Chris Lattner7e6d7452010-06-21 23:12:56 +00001357 }
1358 Out << "(" << opNames[0] << ", "
1359 << getCppName(cst->getType()) << ", \"";
1360 printEscapedString(cst->getName());
1361 Out << "\", " << bbname << ");";
1362 break;
1363 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001364 case Instruction::Call: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001365 const CallInst* call = cast<CallInst>(I);
1366 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1367 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1368 << getCppName(ila->getFunctionType()) << ", \""
1369 << ila->getAsmString() << "\", \""
1370 << ila->getConstraintString() << "\","
1371 << (ila->hasSideEffects() ? "true" : "false") << ");";
1372 nl(Out);
1373 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001374 if (call->getNumArgOperands() > 1) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001375 Out << "std::vector<Value*> " << iName << "_params;";
1376 nl(Out);
Gabor Greif53ba5502010-07-02 19:08:46 +00001377 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
Gabor Greif63d024f2010-07-13 15:31:36 +00001378 Out << iName << "_params.push_back(" << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001379 nl(Out);
1380 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001381 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greifa3997812010-07-22 10:37:47 +00001382 << opNames[call->getNumArgOperands()] << ", "
Nicolas Geoffraya056d202011-07-21 20:59:21 +00001383 << iName << "_params, \"";
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001384 } else if (call->getNumArgOperands() == 1) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001385 Out << "CallInst* " << iName << " = CallInst::Create("
Gabor Greif63d024f2010-07-13 15:31:36 +00001386 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001387 } else {
Gabor Greif63d024f2010-07-13 15:31:36 +00001388 Out << "CallInst* " << iName << " = CallInst::Create("
1389 << opNames[call->getNumArgOperands()] << ", \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001390 }
1391 printEscapedString(call->getName());
1392 Out << "\", " << bbname << ");";
1393 nl(Out) << iName << "->setCallingConv(";
1394 printCallingConv(call->getCallingConv());
1395 Out << ");";
1396 nl(Out) << iName << "->setTailCall("
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001397 << (call->isTailCall() ? "true" : "false");
Chris Lattner7e6d7452010-06-21 23:12:56 +00001398 Out << ");";
Gabor Greif135d7fe2010-07-02 19:26:28 +00001399 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001400 printAttributes(call->getAttributes(), iName);
1401 Out << iName << "->setAttributes(" << iName << "_PAL);";
1402 nl(Out);
1403 break;
1404 }
1405 case Instruction::Select: {
1406 const SelectInst* sel = cast<SelectInst>(I);
1407 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1408 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1409 printEscapedString(sel->getName());
1410 Out << "\", " << bbname << ");";
1411 break;
1412 }
1413 case Instruction::UserOp1:
1414 /// FALL THROUGH
1415 case Instruction::UserOp2: {
1416 /// FIXME: What should be done here?
1417 break;
1418 }
1419 case Instruction::VAArg: {
1420 const VAArgInst* va = cast<VAArgInst>(I);
1421 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1422 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1423 printEscapedString(va->getName());
1424 Out << "\", " << bbname << ");";
1425 break;
1426 }
1427 case Instruction::ExtractElement: {
1428 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1429 Out << "ExtractElementInst* " << getCppName(eei)
1430 << " = new ExtractElementInst(" << opNames[0]
1431 << ", " << opNames[1] << ", \"";
1432 printEscapedString(eei->getName());
1433 Out << "\", " << bbname << ");";
1434 break;
1435 }
1436 case Instruction::InsertElement: {
1437 const InsertElementInst* iei = cast<InsertElementInst>(I);
1438 Out << "InsertElementInst* " << getCppName(iei)
1439 << " = InsertElementInst::Create(" << opNames[0]
1440 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1441 printEscapedString(iei->getName());
1442 Out << "\", " << bbname << ");";
1443 break;
1444 }
1445 case Instruction::ShuffleVector: {
1446 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1447 Out << "ShuffleVectorInst* " << getCppName(svi)
1448 << " = new ShuffleVectorInst(" << opNames[0]
1449 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1450 printEscapedString(svi->getName());
1451 Out << "\", " << bbname << ");";
1452 break;
1453 }
1454 case Instruction::ExtractValue: {
1455 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1456 Out << "std::vector<unsigned> " << iName << "_indices;";
1457 nl(Out);
1458 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1459 Out << iName << "_indices.push_back("
1460 << evi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001461 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001462 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001463 Out << "ExtractValueInst* " << getCppName(evi)
1464 << " = ExtractValueInst::Create(" << opNames[0]
1465 << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001466 << iName << "_indices, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001467 printEscapedString(evi->getName());
1468 Out << "\", " << bbname << ");";
1469 break;
1470 }
1471 case Instruction::InsertValue: {
1472 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1473 Out << "std::vector<unsigned> " << iName << "_indices;";
1474 nl(Out);
1475 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1476 Out << iName << "_indices.push_back("
1477 << ivi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001478 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001479 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001480 Out << "InsertValueInst* " << getCppName(ivi)
1481 << " = InsertValueInst::Create(" << opNames[0]
1482 << ", " << opNames[1] << ", "
Nick Lewycky3bca1012011-09-05 18:50:59 +00001483 << iName << "_indices, \"";
Chris Lattner7e6d7452010-06-21 23:12:56 +00001484 printEscapedString(ivi->getName());
1485 Out << "\", " << bbname << ");";
1486 break;
1487 }
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001488 case Instruction::Fence: {
1489 const FenceInst *fi = cast<FenceInst>(I);
1490 StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1491 StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1492 Out << "FenceInst* " << iName
1493 << " = new FenceInst(mod->getContext(), "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001494 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001495 << ");";
1496 break;
1497 }
1498 case Instruction::AtomicCmpXchg: {
1499 const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1500 StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1501 StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1502 Out << "AtomicCmpXchgInst* " << iName
1503 << " = new AtomicCmpXchgInst("
1504 << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001505 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001506 << ");";
1507 nl(Out) << iName << "->setName(\"";
1508 printEscapedString(cxi->getName());
1509 Out << "\");";
1510 break;
1511 }
1512 case Instruction::AtomicRMW: {
1513 const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1514 StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1515 StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1516 StringRef Operation;
1517 switch (rmwi->getOperation()) {
1518 case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1519 case AtomicRMWInst::Add: Operation = "AtomicRMWInst::Add"; break;
1520 case AtomicRMWInst::Sub: Operation = "AtomicRMWInst::Sub"; break;
1521 case AtomicRMWInst::And: Operation = "AtomicRMWInst::And"; break;
1522 case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1523 case AtomicRMWInst::Or: Operation = "AtomicRMWInst::Or"; break;
1524 case AtomicRMWInst::Xor: Operation = "AtomicRMWInst::Xor"; break;
1525 case AtomicRMWInst::Max: Operation = "AtomicRMWInst::Max"; break;
1526 case AtomicRMWInst::Min: Operation = "AtomicRMWInst::Min"; break;
1527 case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1528 case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1529 case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1530 }
1531 Out << "AtomicRMWInst* " << iName
1532 << " = new AtomicRMWInst("
1533 << Operation << ", "
1534 << opNames[0] << ", " << opNames[1] << ", "
Eli Friedman5b7cc332011-11-04 17:29:35 +00001535 << Ordering << ", " << CrossThread << ", " << bbname
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001536 << ");";
1537 nl(Out) << iName << "->setName(\"";
1538 printEscapedString(rmwi->getName());
1539 Out << "\");";
1540 break;
1541 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001542 }
1543 DefinedValues.insert(I);
1544 nl(Out);
1545 delete [] opNames;
1546}
1547
Chris Lattner7e6d7452010-06-21 23:12:56 +00001548// Print out the types, constants and declarations needed by one function
1549void CppWriter::printFunctionUses(const Function* F) {
1550 nl(Out) << "// Type Definitions"; nl(Out);
1551 if (!is_inline) {
1552 // Print the function's return type
1553 printType(F->getReturnType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001554
Chris Lattner7e6d7452010-06-21 23:12:56 +00001555 // Print the function's function type
1556 printType(F->getFunctionType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001557
Chris Lattner7e6d7452010-06-21 23:12:56 +00001558 // Print the types of each of the function's arguments
Anton Korobeynikov50276522008-04-23 22:29:24 +00001559 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1560 AI != AE; ++AI) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001561 printType(AI->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001562 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001563 }
1564
Chris Lattner7e6d7452010-06-21 23:12:56 +00001565 // Print type definitions for every type referenced by an instruction and
1566 // make a note of any global values or constants that are referenced
1567 SmallPtrSet<GlobalValue*,64> gvs;
1568 SmallPtrSet<Constant*,64> consts;
1569 for (Function::const_iterator BB = F->begin(), BE = F->end();
1570 BB != BE; ++BB){
1571 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001572 I != E; ++I) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001573 // Print the type of the instruction itself
1574 printType(I->getType());
1575
1576 // Print the type of each of the instruction's operands
1577 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1578 Value* operand = I->getOperand(i);
1579 printType(operand->getType());
1580
1581 // If the operand references a GVal or Constant, make a note of it
1582 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1583 gvs.insert(GV);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001584 if (GenerationType != GenFunction)
1585 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1586 if (GVar->hasInitializer())
1587 consts.insert(GVar->getInitializer());
1588 } else if (Constant* C = dyn_cast<Constant>(operand)) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001589 consts.insert(C);
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001590 for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1591 // If the operand references a GVal or Constant, make a note of it
1592 Value* operand = C->getOperand(j);
1593 printType(operand->getType());
1594 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1595 gvs.insert(GV);
1596 if (GenerationType != GenFunction)
1597 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1598 if (GVar->hasInitializer())
1599 consts.insert(GVar->getInitializer());
1600 }
1601 }
1602 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001603 }
1604 }
1605 }
1606
1607 // Print the function declarations for any functions encountered
1608 nl(Out) << "// Function Declarations"; nl(Out);
1609 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1610 I != E; ++I) {
1611 if (Function* Fun = dyn_cast<Function>(*I)) {
1612 if (!is_inline || Fun != F)
1613 printFunctionHead(Fun);
1614 }
1615 }
1616
1617 // Print the global variable declarations for any variables encountered
1618 nl(Out) << "// Global Variable Declarations"; nl(Out);
1619 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1620 I != E; ++I) {
1621 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1622 printVariableHead(F);
1623 }
1624
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001625 // Print the constants found
Chris Lattner7e6d7452010-06-21 23:12:56 +00001626 nl(Out) << "// Constant Definitions"; nl(Out);
1627 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1628 E = consts.end(); I != E; ++I) {
1629 printConstant(*I);
1630 }
1631
1632 // Process the global variables definitions now that all the constants have
1633 // been emitted. These definitions just couple the gvars with their constant
1634 // initializers.
Nicolas Geoffray7509ccd2010-11-28 18:00:53 +00001635 if (GenerationType != GenFunction) {
1636 nl(Out) << "// Global Variable Definitions"; nl(Out);
1637 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1638 I != E; ++I) {
1639 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1640 printVariableBody(GV);
1641 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001642 }
1643}
1644
1645void CppWriter::printFunctionHead(const Function* F) {
1646 nl(Out) << "Function* " << getCppName(F);
Nicolas Geoffrayf8557952011-10-08 11:56:36 +00001647 Out << " = mod->getFunction(\"";
1648 printEscapedString(F->getName());
1649 Out << "\");";
1650 nl(Out) << "if (!" << getCppName(F) << ") {";
1651 nl(Out) << getCppName(F);
1652
Chris Lattner7e6d7452010-06-21 23:12:56 +00001653 Out<< " = Function::Create(";
1654 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1655 nl(Out) << "/*Linkage=*/";
1656 printLinkageType(F->getLinkage());
1657 Out << ",";
1658 nl(Out) << "/*Name=*/\"";
1659 printEscapedString(F->getName());
1660 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1661 nl(Out,-1);
1662 printCppName(F);
1663 Out << "->setCallingConv(";
1664 printCallingConv(F->getCallingConv());
1665 Out << ");";
1666 nl(Out);
1667 if (F->hasSection()) {
1668 printCppName(F);
1669 Out << "->setSection(\"" << F->getSection() << "\");";
1670 nl(Out);
1671 }
1672 if (F->getAlignment()) {
1673 printCppName(F);
1674 Out << "->setAlignment(" << F->getAlignment() << ");";
1675 nl(Out);
1676 }
1677 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1678 printCppName(F);
1679 Out << "->setVisibility(";
1680 printVisibilityType(F->getVisibility());
1681 Out << ");";
1682 nl(Out);
1683 }
1684 if (F->hasGC()) {
1685 printCppName(F);
1686 Out << "->setGC(\"" << F->getGC() << "\");";
1687 nl(Out);
1688 }
Nicolas Geoffrayf8557952011-10-08 11:56:36 +00001689 Out << "}";
1690 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001691 printAttributes(F->getAttributes(), getCppName(F));
1692 printCppName(F);
1693 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1694 nl(Out);
1695}
1696
1697void CppWriter::printFunctionBody(const Function *F) {
1698 if (F->isDeclaration())
1699 return; // external functions have no bodies.
1700
1701 // Clear the DefinedValues and ForwardRefs maps because we can't have
1702 // cross-function forward refs
1703 ForwardRefs.clear();
1704 DefinedValues.clear();
1705
1706 // Create all the argument values
1707 if (!is_inline) {
1708 if (!F->arg_empty()) {
1709 Out << "Function::arg_iterator args = " << getCppName(F)
1710 << "->arg_begin();";
1711 nl(Out);
1712 }
1713 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1714 AI != AE; ++AI) {
1715 Out << "Value* " << getCppName(AI) << " = args++;";
1716 nl(Out);
1717 if (AI->hasName()) {
Eli Friedmana7dd4df2011-10-31 23:59:22 +00001718 Out << getCppName(AI) << "->setName(\"";
1719 printEscapedString(AI->getName());
1720 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001721 nl(Out);
1722 }
1723 }
1724 }
1725
Chris Lattner7e6d7452010-06-21 23:12:56 +00001726 // Create all the basic blocks
1727 nl(Out);
1728 for (Function::const_iterator BI = F->begin(), BE = F->end();
1729 BI != BE; ++BI) {
1730 std::string bbname(getCppName(BI));
1731 Out << "BasicBlock* " << bbname <<
1732 " = BasicBlock::Create(mod->getContext(), \"";
1733 if (BI->hasName())
1734 printEscapedString(BI->getName());
1735 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1736 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001737 }
1738
Chris Lattner7e6d7452010-06-21 23:12:56 +00001739 // Output all of its basic blocks... for the function
1740 for (Function::const_iterator BI = F->begin(), BE = F->end();
1741 BI != BE; ++BI) {
1742 std::string bbname(getCppName(BI));
1743 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001744 nl(Out);
1745
Chris Lattner7e6d7452010-06-21 23:12:56 +00001746 // Output all of the instructions in the basic block...
1747 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1748 I != E; ++I) {
1749 printInstruction(I,bbname);
1750 }
1751 }
1752
1753 // Loop over the ForwardRefs and resolve them now that all instructions
1754 // are generated.
1755 if (!ForwardRefs.empty()) {
1756 nl(Out) << "// Resolve Forward References";
1757 nl(Out);
1758 }
1759
1760 while (!ForwardRefs.empty()) {
1761 ForwardRefMap::iterator I = ForwardRefs.begin();
1762 Out << I->second << "->replaceAllUsesWith("
1763 << getCppName(I->first) << "); delete " << I->second << ";";
1764 nl(Out);
1765 ForwardRefs.erase(I);
1766 }
1767}
1768
1769void CppWriter::printInline(const std::string& fname,
1770 const std::string& func) {
1771 const Function* F = TheModule->getFunction(func);
1772 if (!F) {
1773 error(std::string("Function '") + func + "' not found in input module");
1774 return;
1775 }
1776 if (F->isDeclaration()) {
1777 error(std::string("Function '") + func + "' is external!");
1778 return;
1779 }
1780 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1781 << getCppName(F);
1782 unsigned arg_count = 1;
1783 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1784 AI != AE; ++AI) {
1785 Out << ", Value* arg_" << arg_count;
1786 }
1787 Out << ") {";
1788 nl(Out);
1789 is_inline = true;
1790 printFunctionUses(F);
1791 printFunctionBody(F);
1792 is_inline = false;
1793 Out << "return " << getCppName(F->begin()) << ";";
1794 nl(Out) << "}";
1795 nl(Out);
1796}
1797
1798void CppWriter::printModuleBody() {
1799 // Print out all the type definitions
1800 nl(Out) << "// Type Definitions"; nl(Out);
1801 printTypes(TheModule);
1802
1803 // Functions can call each other and global variables can reference them so
1804 // define all the functions first before emitting their function bodies.
1805 nl(Out) << "// Function Declarations"; nl(Out);
1806 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1807 I != E; ++I)
1808 printFunctionHead(I);
1809
1810 // Process the global variables declarations. We can't initialze them until
1811 // after the constants are printed so just print a header for each global
1812 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1813 for (Module::const_global_iterator I = TheModule->global_begin(),
1814 E = TheModule->global_end(); I != E; ++I) {
1815 printVariableHead(I);
1816 }
1817
1818 // Print out all the constants definitions. Constants don't recurse except
1819 // through GlobalValues. All GlobalValues have been declared at this point
1820 // so we can proceed to generate the constants.
1821 nl(Out) << "// Constant Definitions"; nl(Out);
1822 printConstants(TheModule);
1823
1824 // Process the global variables definitions now that all the constants have
1825 // been emitted. These definitions just couple the gvars with their constant
1826 // initializers.
1827 nl(Out) << "// Global Variable Definitions"; nl(Out);
1828 for (Module::const_global_iterator I = TheModule->global_begin(),
1829 E = TheModule->global_end(); I != E; ++I) {
1830 printVariableBody(I);
1831 }
1832
1833 // Finally, we can safely put out all of the function bodies.
1834 nl(Out) << "// Function Definitions"; nl(Out);
1835 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1836 I != E; ++I) {
1837 if (!I->isDeclaration()) {
1838 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1839 << ")";
1840 nl(Out) << "{";
1841 nl(Out,1);
1842 printFunctionBody(I);
1843 nl(Out,-1) << "}";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001844 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001845 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001846 }
1847}
1848
1849void CppWriter::printProgram(const std::string& fname,
1850 const std::string& mName) {
1851 Out << "#include <llvm/LLVMContext.h>\n";
1852 Out << "#include <llvm/Module.h>\n";
1853 Out << "#include <llvm/DerivedTypes.h>\n";
1854 Out << "#include <llvm/Constants.h>\n";
1855 Out << "#include <llvm/GlobalVariable.h>\n";
1856 Out << "#include <llvm/Function.h>\n";
1857 Out << "#include <llvm/CallingConv.h>\n";
1858 Out << "#include <llvm/BasicBlock.h>\n";
1859 Out << "#include <llvm/Instructions.h>\n";
1860 Out << "#include <llvm/InlineAsm.h>\n";
1861 Out << "#include <llvm/Support/FormattedStream.h>\n";
1862 Out << "#include <llvm/Support/MathExtras.h>\n";
1863 Out << "#include <llvm/Pass.h>\n";
1864 Out << "#include <llvm/PassManager.h>\n";
1865 Out << "#include <llvm/ADT/SmallVector.h>\n";
1866 Out << "#include <llvm/Analysis/Verifier.h>\n";
1867 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1868 Out << "#include <algorithm>\n";
1869 Out << "using namespace llvm;\n\n";
1870 Out << "Module* " << fname << "();\n\n";
1871 Out << "int main(int argc, char**argv) {\n";
1872 Out << " Module* Mod = " << fname << "();\n";
1873 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1874 Out << " PassManager PM;\n";
1875 Out << " PM.add(createPrintModulePass(&outs()));\n";
1876 Out << " PM.run(*Mod);\n";
1877 Out << " return 0;\n";
1878 Out << "}\n\n";
1879 printModule(fname,mName);
1880}
1881
1882void CppWriter::printModule(const std::string& fname,
1883 const std::string& mName) {
1884 nl(Out) << "Module* " << fname << "() {";
1885 nl(Out,1) << "// Module Construction";
1886 nl(Out) << "Module* mod = new Module(\"";
1887 printEscapedString(mName);
1888 Out << "\", getGlobalContext());";
1889 if (!TheModule->getTargetTriple().empty()) {
1890 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1891 }
1892 if (!TheModule->getTargetTriple().empty()) {
1893 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1894 << "\");";
1895 }
1896
1897 if (!TheModule->getModuleInlineAsm().empty()) {
1898 nl(Out) << "mod->setModuleInlineAsm(\"";
1899 printEscapedString(TheModule->getModuleInlineAsm());
1900 Out << "\");";
1901 }
1902 nl(Out);
1903
1904 // Loop over the dependent libraries and emit them.
1905 Module::lib_iterator LI = TheModule->lib_begin();
1906 Module::lib_iterator LE = TheModule->lib_end();
1907 while (LI != LE) {
1908 Out << "mod->addLibrary(\"" << *LI << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001909 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001910 ++LI;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001911 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001912 printModuleBody();
1913 nl(Out) << "return mod;";
1914 nl(Out,-1) << "}";
1915 nl(Out);
1916}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001917
Chris Lattner7e6d7452010-06-21 23:12:56 +00001918void CppWriter::printContents(const std::string& fname,
1919 const std::string& mName) {
1920 Out << "\nModule* " << fname << "(Module *mod) {\n";
1921 Out << "\nmod->setModuleIdentifier(\"";
1922 printEscapedString(mName);
1923 Out << "\");\n";
1924 printModuleBody();
1925 Out << "\nreturn mod;\n";
1926 Out << "\n}\n";
1927}
1928
1929void CppWriter::printFunction(const std::string& fname,
1930 const std::string& funcName) {
1931 const Function* F = TheModule->getFunction(funcName);
1932 if (!F) {
1933 error(std::string("Function '") + funcName + "' not found in input module");
1934 return;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001935 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001936 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1937 printFunctionUses(F);
1938 printFunctionHead(F);
1939 printFunctionBody(F);
1940 Out << "return " << getCppName(F) << ";\n";
1941 Out << "}\n";
1942}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001943
Chris Lattner7e6d7452010-06-21 23:12:56 +00001944void CppWriter::printFunctions() {
1945 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1946 Module::const_iterator I = funcs.begin();
1947 Module::const_iterator IE = funcs.end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001948
Chris Lattner7e6d7452010-06-21 23:12:56 +00001949 for (; I != IE; ++I) {
1950 const Function &func = *I;
1951 if (!func.isDeclaration()) {
1952 std::string name("define_");
1953 name += func.getName();
1954 printFunction(name, func.getName());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001955 }
1956 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001957}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001958
Chris Lattner7e6d7452010-06-21 23:12:56 +00001959void CppWriter::printVariable(const std::string& fname,
1960 const std::string& varName) {
1961 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001962
Chris Lattner7e6d7452010-06-21 23:12:56 +00001963 if (!GV) {
1964 error(std::string("Variable '") + varName + "' not found in input module");
1965 return;
1966 }
1967 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1968 printVariableUses(GV);
1969 printVariableHead(GV);
1970 printVariableBody(GV);
1971 Out << "return " << getCppName(GV) << ";\n";
1972 Out << "}\n";
1973}
1974
Chris Lattner1afcace2011-07-09 17:41:24 +00001975void CppWriter::printType(const std::string &fname,
1976 const std::string &typeName) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001977 Type* Ty = TheModule->getTypeByName(typeName);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001978 if (!Ty) {
1979 error(std::string("Type '") + typeName + "' not found in input module");
1980 return;
1981 }
1982 Out << "\nType* " << fname << "(Module *mod) {\n";
1983 printType(Ty);
1984 Out << "return " << getCppName(Ty) << ";\n";
1985 Out << "}\n";
1986}
1987
1988bool CppWriter::runOnModule(Module &M) {
1989 TheModule = &M;
1990
1991 // Emit a header
1992 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1993
1994 // Get the name of the function we're supposed to generate
1995 std::string fname = FuncName.getValue();
1996
1997 // Get the name of the thing we are to generate
1998 std::string tgtname = NameToGenerate.getValue();
1999 if (GenerationType == GenModule ||
2000 GenerationType == GenContents ||
2001 GenerationType == GenProgram ||
2002 GenerationType == GenFunctions) {
2003 if (tgtname == "!bad!") {
2004 if (M.getModuleIdentifier() == "-")
2005 tgtname = "<stdin>";
2006 else
2007 tgtname = M.getModuleIdentifier();
Anton Korobeynikov50276522008-04-23 22:29:24 +00002008 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00002009 } else if (tgtname == "!bad!")
2010 error("You must use the -for option with -gen-{function,variable,type}");
2011
2012 switch (WhatToGenerate(GenerationType)) {
2013 case GenProgram:
2014 if (fname.empty())
2015 fname = "makeLLVMModule";
2016 printProgram(fname,tgtname);
2017 break;
2018 case GenModule:
2019 if (fname.empty())
2020 fname = "makeLLVMModule";
2021 printModule(fname,tgtname);
2022 break;
2023 case GenContents:
2024 if (fname.empty())
2025 fname = "makeLLVMModuleContents";
2026 printContents(fname,tgtname);
2027 break;
2028 case GenFunction:
2029 if (fname.empty())
2030 fname = "makeLLVMFunction";
2031 printFunction(fname,tgtname);
2032 break;
2033 case GenFunctions:
2034 printFunctions();
2035 break;
2036 case GenInline:
2037 if (fname.empty())
2038 fname = "makeLLVMInline";
2039 printInline(fname,tgtname);
2040 break;
2041 case GenVariable:
2042 if (fname.empty())
2043 fname = "makeLLVMVariable";
2044 printVariable(fname,tgtname);
2045 break;
2046 case GenType:
2047 if (fname.empty())
2048 fname = "makeLLVMType";
2049 printType(fname,tgtname);
2050 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002051 }
2052
Chris Lattner7e6d7452010-06-21 23:12:56 +00002053 return false;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002054}
2055
2056char CppWriter::ID = 0;
2057
2058//===----------------------------------------------------------------------===//
2059// External Interface declaration
2060//===----------------------------------------------------------------------===//
2061
Dan Gohman99dca4f2010-05-11 19:57:55 +00002062bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2063 formatted_raw_ostream &o,
2064 CodeGenFileType FileType,
Dan Gohman99dca4f2010-05-11 19:57:55 +00002065 bool DisableVerify) {
Chris Lattner211edae2010-02-02 21:06:45 +00002066 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002067 PM.add(new CppWriter(o));
2068 return false;
2069}