blob: eda08e7a88952ae9cbfeded9af8a988532d19dc3 [file] [log] [blame]
Anton Korobeynikov50276522008-04-23 22:29:24 +00001//===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the writing of the LLVM IR as a set of C++ calls to the
11// LLVM IR interface. The input module is assumed to be verified.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CPPTargetMachine.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instruction.h"
21#include "llvm/Instructions.h"
22#include "llvm/Module.h"
23#include "llvm/Pass.h"
24#include "llvm/PassManager.h"
25#include "llvm/TypeSymbolTable.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000026#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/Support/CommandLine.h"
Torok Edwin30464702009-07-08 20:55:50 +000028#include "llvm/Support/ErrorHandling.h"
David Greene71847812009-07-14 20:18:05 +000029#include "llvm/Support/FormattedStream.h"
Daniel Dunbar0c795d62009-07-25 06:49:55 +000030#include "llvm/Target/TargetRegistry.h"
Chris Lattner23132b12009-08-24 03:52:50 +000031#include "llvm/ADT/StringExtras.h"
Anton Korobeynikov50276522008-04-23 22:29:24 +000032#include "llvm/Config/config.h"
33#include <algorithm>
Anton Korobeynikov50276522008-04-23 22:29:24 +000034#include <set>
35
36using namespace llvm;
37
38static cl::opt<std::string>
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000039FuncName("cppfname", cl::desc("Specify the name of the generated function"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000040 cl::value_desc("function name"));
41
42enum WhatToGenerate {
43 GenProgram,
44 GenModule,
45 GenContents,
46 GenFunction,
47 GenFunctions,
48 GenInline,
49 GenVariable,
50 GenType
51};
52
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000053static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000054 cl::desc("Choose what kind of output to generate"),
55 cl::init(GenProgram),
56 cl::values(
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000057 clEnumValN(GenProgram, "program", "Generate a complete program"),
58 clEnumValN(GenModule, "module", "Generate a module definition"),
59 clEnumValN(GenContents, "contents", "Generate contents of a module"),
60 clEnumValN(GenFunction, "function", "Generate a function definition"),
61 clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
62 clEnumValN(GenInline, "inline", "Generate an inline function"),
63 clEnumValN(GenVariable, "variable", "Generate a variable definition"),
64 clEnumValN(GenType, "type", "Generate a type definition"),
Anton Korobeynikov50276522008-04-23 22:29:24 +000065 clEnumValEnd
66 )
67);
68
Anton Korobeynikov8d3e74e2008-04-23 22:37:03 +000069static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
Anton Korobeynikov50276522008-04-23 22:29:24 +000070 cl::desc("Specify the name of the thing to generate"),
71 cl::init("!bad!"));
72
Daniel Dunbar0c795d62009-07-25 06:49:55 +000073extern "C" void LLVMInitializeCppBackendTarget() {
74 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000075 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000076}
Douglas Gregor1555a232009-06-16 20:12:29 +000077
Dan Gohman844731a2008-05-13 00:00:25 +000078namespace {
Anton Korobeynikov50276522008-04-23 22:29:24 +000079 typedef std::vector<const Type*> TypeList;
80 typedef std::map<const Type*,std::string> TypeMap;
81 typedef std::map<const Value*,std::string> ValueMap;
82 typedef std::set<std::string> NameSet;
83 typedef std::set<const Type*> TypeSet;
84 typedef std::set<const Value*> ValueSet;
85 typedef std::map<const Value*,std::string> ForwardRefMap;
86
87 /// CppWriter - This class is the main chunk of code that converts an LLVM
88 /// module to a C++ translation unit.
89 class CppWriter : public ModulePass {
David Greene71847812009-07-14 20:18:05 +000090 formatted_raw_ostream &Out;
Anton Korobeynikov50276522008-04-23 22:29:24 +000091 const Module *TheModule;
92 uint64_t uniqueNum;
93 TypeMap TypeNames;
94 ValueMap ValueNames;
95 TypeMap UnresolvedTypes;
96 TypeList TypeStack;
97 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) :
Chris Lattnerceea3012010-06-22 00:40:26 +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
136 std::string getCppName(const Type* val);
137 inline void printCppName(const Type* val);
138
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);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000143 bool printTypeInternal(const Type* Ty);
144 inline void printType(const Type* Ty);
145 void printTypes(const Module* M);
146
147 void printConstant(const Constant *CPV);
148 void printConstants(const Module* M);
149
150 void printVariableUses(const GlobalVariable *GV);
151 void printVariableHead(const GlobalVariable *GV);
152 void printVariableBody(const GlobalVariable *GV);
153
154 void printFunctionUses(const Function *F);
155 void printFunctionHead(const Function *F);
156 void printFunctionBody(const Function *F);
157 void printInstruction(const Instruction *I, const std::string& bbname);
158 std::string getOpName(Value*);
159
160 void printModuleBody();
161 };
Chris Lattner7e6d7452010-06-21 23:12:56 +0000162} // end anonymous namespace.
Anton Korobeynikov50276522008-04-23 22:29:24 +0000163
Chris Lattner1018c242010-06-21 23:14:47 +0000164formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
165 Out << '\n';
Chris Lattner7e6d7452010-06-21 23:12:56 +0000166 if (delta >= 0 || indent_level >= unsigned(-delta))
167 indent_level += delta;
Chris Lattner1018c242010-06-21 23:14:47 +0000168 Out.indent(indent_level);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000169 return Out;
170}
171
Chris Lattner7e6d7452010-06-21 23:12:56 +0000172static inline void sanitize(std::string &str) {
173 for (size_t i = 0; i < str.length(); ++i)
174 if (!isalnum(str[i]) && str[i] != '_')
175 str[i] = '_';
176}
177
178static std::string getTypePrefix(const Type *Ty) {
179 switch (Ty->getTypeID()) {
180 case Type::VoidTyID: return "void_";
181 case Type::IntegerTyID:
182 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
183 case Type::FloatTyID: return "float_";
184 case Type::DoubleTyID: return "double_";
185 case Type::LabelTyID: return "label_";
186 case Type::FunctionTyID: return "func_";
187 case Type::StructTyID: return "struct_";
188 case Type::ArrayTyID: return "array_";
189 case Type::PointerTyID: return "ptr_";
190 case Type::VectorTyID: return "packed_";
191 case Type::OpaqueTyID: return "opaque_";
192 default: return "other_";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000193 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000194 return "unknown_";
195}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000196
Chris Lattner7e6d7452010-06-21 23:12:56 +0000197// Looks up the type in the symbol table and returns a pointer to its name or
198// a null pointer if it wasn't found. Note that this isn't the same as the
199// Mode::getTypeName function which will return an empty string, not a null
200// pointer if the name is not found.
201static const std::string *
202findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
203 TypeSymbolTable::const_iterator TI = ST.begin();
204 TypeSymbolTable::const_iterator TE = ST.end();
205 for (;TI != TE; ++TI)
206 if (TI->second == Ty)
207 return &(TI->first);
208 return 0;
209}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000210
Chris Lattner7e6d7452010-06-21 23:12:56 +0000211void CppWriter::error(const std::string& msg) {
212 report_fatal_error(msg);
213}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000214
Chris Lattner7e6d7452010-06-21 23:12:56 +0000215// printCFP - Print a floating point constant .. very carefully :)
216// This makes sure that conversion to/from floating yields the same binary
217// result so that we don't lose precision.
218void CppWriter::printCFP(const ConstantFP *CFP) {
219 bool ignored;
220 APFloat APF = APFloat(CFP->getValueAPF()); // copy
221 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
222 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
223 Out << "ConstantFP::get(mod->getContext(), ";
224 Out << "APFloat(";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000225#if HAVE_PRINTF_A
Chris Lattner7e6d7452010-06-21 23:12:56 +0000226 char Buffer[100];
227 sprintf(Buffer, "%A", APF.convertToDouble());
228 if ((!strncmp(Buffer, "0x", 2) ||
229 !strncmp(Buffer, "-0x", 3) ||
230 !strncmp(Buffer, "+0x", 3)) &&
231 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
232 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
233 Out << "BitsToDouble(" << Buffer << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000234 else
Chris Lattner7e6d7452010-06-21 23:12:56 +0000235 Out << "BitsToFloat((float)" << Buffer << ")";
236 Out << ")";
237 } else {
238#endif
239 std::string StrVal = ftostr(CFP->getValueAPF());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000240
Chris Lattner7e6d7452010-06-21 23:12:56 +0000241 while (StrVal[0] == ' ')
242 StrVal.erase(StrVal.begin());
243
244 // Check to make sure that the stringized number is not some string like
245 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
246 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
247 ((StrVal[0] == '-' || StrVal[0] == '+') &&
248 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
249 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
250 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
251 Out << StrVal;
252 else
253 Out << StrVal << "f";
254 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
255 Out << "BitsToDouble(0x"
256 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
257 << "ULL) /* " << StrVal << " */";
258 else
259 Out << "BitsToFloat(0x"
260 << utohexstr((uint32_t)CFP->getValueAPF().
261 bitcastToAPInt().getZExtValue())
262 << "U) /* " << StrVal << " */";
263 Out << ")";
264#if HAVE_PRINTF_A
265 }
266#endif
267 Out << ")";
268}
269
270void CppWriter::printCallingConv(CallingConv::ID cc){
271 // Print the calling convention.
272 switch (cc) {
273 case CallingConv::C: Out << "CallingConv::C"; break;
274 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
275 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
276 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
277 default: Out << cc; break;
278 }
279}
280
281void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
282 switch (LT) {
283 case GlobalValue::InternalLinkage:
284 Out << "GlobalValue::InternalLinkage"; break;
285 case GlobalValue::PrivateLinkage:
286 Out << "GlobalValue::PrivateLinkage"; break;
287 case GlobalValue::LinkerPrivateLinkage:
288 Out << "GlobalValue::LinkerPrivateLinkage"; break;
289 case GlobalValue::AvailableExternallyLinkage:
290 Out << "GlobalValue::AvailableExternallyLinkage "; break;
291 case GlobalValue::LinkOnceAnyLinkage:
292 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
293 case GlobalValue::LinkOnceODRLinkage:
294 Out << "GlobalValue::LinkOnceODRLinkage "; break;
295 case GlobalValue::WeakAnyLinkage:
296 Out << "GlobalValue::WeakAnyLinkage"; break;
297 case GlobalValue::WeakODRLinkage:
298 Out << "GlobalValue::WeakODRLinkage"; break;
299 case GlobalValue::AppendingLinkage:
300 Out << "GlobalValue::AppendingLinkage"; break;
301 case GlobalValue::ExternalLinkage:
302 Out << "GlobalValue::ExternalLinkage"; break;
303 case GlobalValue::DLLImportLinkage:
304 Out << "GlobalValue::DLLImportLinkage"; break;
305 case GlobalValue::DLLExportLinkage:
306 Out << "GlobalValue::DLLExportLinkage"; break;
307 case GlobalValue::ExternalWeakLinkage:
308 Out << "GlobalValue::ExternalWeakLinkage"; break;
309 case GlobalValue::CommonLinkage:
310 Out << "GlobalValue::CommonLinkage"; break;
311 }
312}
313
314void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
315 switch (VisType) {
316 default: llvm_unreachable("Unknown GVar visibility");
317 case GlobalValue::DefaultVisibility:
318 Out << "GlobalValue::DefaultVisibility";
319 break;
320 case GlobalValue::HiddenVisibility:
321 Out << "GlobalValue::HiddenVisibility";
322 break;
323 case GlobalValue::ProtectedVisibility:
324 Out << "GlobalValue::ProtectedVisibility";
325 break;
326 }
327}
328
329// printEscapedString - Print each character of the specified string, escaping
330// it if it is not printable or if it is an escape char.
331void CppWriter::printEscapedString(const std::string &Str) {
332 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
333 unsigned char C = Str[i];
334 if (isprint(C) && C != '"' && C != '\\') {
335 Out << C;
336 } else {
337 Out << "\\x"
338 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
339 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
340 }
341 }
342}
343
344std::string CppWriter::getCppName(const Type* Ty) {
345 // First, handle the primitive types .. easy
346 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
347 switch (Ty->getTypeID()) {
348 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())";
349 case Type::IntegerTyID: {
350 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
351 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
352 }
353 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
354 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())";
355 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())";
356 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())";
357 default:
358 error("Invalid primitive type");
359 break;
360 }
361 // shouldn't be returned, but make it sensible
362 return "Type::getVoidTy(mod->getContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000363 }
364
Chris Lattner7e6d7452010-06-21 23:12:56 +0000365 // Now, see if we've seen the type before and return that
366 TypeMap::iterator I = TypeNames.find(Ty);
367 if (I != TypeNames.end())
368 return I->second;
369
370 // Okay, let's build a new name for this type. Start with a prefix
371 const char* prefix = 0;
372 switch (Ty->getTypeID()) {
373 case Type::FunctionTyID: prefix = "FuncTy_"; break;
374 case Type::StructTyID: prefix = "StructTy_"; break;
375 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
376 case Type::PointerTyID: prefix = "PointerTy_"; break;
377 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
378 case Type::VectorTyID: prefix = "VectorTy_"; break;
379 default: prefix = "OtherTy_"; break; // prevent breakage
Anton Korobeynikov50276522008-04-23 22:29:24 +0000380 }
381
Chris Lattner7e6d7452010-06-21 23:12:56 +0000382 // See if the type has a name in the symboltable and build accordingly
383 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
384 std::string name;
385 if (tName)
386 name = std::string(prefix) + *tName;
387 else
388 name = std::string(prefix) + utostr(uniqueNum++);
389 sanitize(name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000390
Chris Lattner7e6d7452010-06-21 23:12:56 +0000391 // Save the name
392 return TypeNames[Ty] = name;
393}
394
395void CppWriter::printCppName(const Type* Ty) {
396 printEscapedString(getCppName(Ty));
397}
398
399std::string CppWriter::getCppName(const Value* val) {
400 std::string name;
401 ValueMap::iterator I = ValueNames.find(val);
402 if (I != ValueNames.end() && I->first == val)
403 return I->second;
404
405 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
406 name = std::string("gvar_") +
407 getTypePrefix(GV->getType()->getElementType());
408 } else if (isa<Function>(val)) {
409 name = std::string("func_");
410 } else if (const Constant* C = dyn_cast<Constant>(val)) {
411 name = std::string("const_") + getTypePrefix(C->getType());
412 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
413 if (is_inline) {
414 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
415 Function::const_arg_iterator(Arg)) + 1;
416 name = std::string("arg_") + utostr(argNum);
417 NameSet::iterator NI = UsedNames.find(name);
418 if (NI != UsedNames.end())
419 name += std::string("_") + utostr(uniqueNum++);
420 UsedNames.insert(name);
421 return ValueNames[val] = name;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000422 } else {
423 name = getTypePrefix(val->getType());
424 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000425 } else {
426 name = getTypePrefix(val->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000427 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000428 if (val->hasName())
429 name += val->getName();
430 else
431 name += utostr(uniqueNum++);
432 sanitize(name);
433 NameSet::iterator NI = UsedNames.find(name);
434 if (NI != UsedNames.end())
435 name += std::string("_") + utostr(uniqueNum++);
436 UsedNames.insert(name);
437 return ValueNames[val] = name;
438}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000439
Chris Lattner7e6d7452010-06-21 23:12:56 +0000440void CppWriter::printCppName(const Value* val) {
441 printEscapedString(getCppName(val));
442}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000443
Chris Lattner7e6d7452010-06-21 23:12:56 +0000444void CppWriter::printAttributes(const AttrListPtr &PAL,
445 const std::string &name) {
446 Out << "AttrListPtr " << name << "_PAL;";
447 nl(Out);
448 if (!PAL.isEmpty()) {
449 Out << '{'; in(); nl(Out);
450 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
451 Out << "AttributeWithIndex PAWI;"; nl(Out);
452 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
453 unsigned index = PAL.getSlot(i).Index;
454 Attributes attrs = PAL.getSlot(i).Attrs;
455 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
Chris Lattneracca9552009-01-13 07:22:22 +0000456#define HANDLE_ATTR(X) \
Chris Lattner7e6d7452010-06-21 23:12:56 +0000457 if (attrs & Attribute::X) \
458 Out << " | Attribute::" #X; \
459 attrs &= ~Attribute::X;
460
461 HANDLE_ATTR(SExt);
462 HANDLE_ATTR(ZExt);
463 HANDLE_ATTR(NoReturn);
464 HANDLE_ATTR(InReg);
465 HANDLE_ATTR(StructRet);
466 HANDLE_ATTR(NoUnwind);
467 HANDLE_ATTR(NoAlias);
468 HANDLE_ATTR(ByVal);
469 HANDLE_ATTR(Nest);
470 HANDLE_ATTR(ReadNone);
471 HANDLE_ATTR(ReadOnly);
472 HANDLE_ATTR(InlineHint);
473 HANDLE_ATTR(NoInline);
474 HANDLE_ATTR(AlwaysInline);
475 HANDLE_ATTR(OptimizeForSize);
476 HANDLE_ATTR(StackProtect);
477 HANDLE_ATTR(StackProtectReq);
478 HANDLE_ATTR(NoCapture);
Chris Lattneracca9552009-01-13 07:22:22 +0000479#undef HANDLE_ATTR
Chris Lattner7e6d7452010-06-21 23:12:56 +0000480 assert(attrs == 0 && "Unhandled attribute!");
481 Out << ";";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000482 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000483 Out << "Attrs.push_back(PAWI);";
484 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000485 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000486 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
487 nl(Out);
488 out(); nl(Out);
489 Out << '}'; nl(Out);
490 }
491}
492
493bool CppWriter::printTypeInternal(const Type* Ty) {
494 // We don't print definitions for primitive types
495 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
496 return false;
497
498 // If we already defined this type, we don't need to define it again.
499 if (DefinedTypes.find(Ty) != DefinedTypes.end())
500 return false;
501
502 // Everything below needs the name for the type so get it now.
503 std::string typeName(getCppName(Ty));
504
505 // Search the type stack for recursion. If we find it, then generate this
506 // as an OpaqueType, but make sure not to do this multiple times because
507 // the type could appear in multiple places on the stack. Once the opaque
508 // definition is issued, it must not be re-issued. Consequently we have to
509 // check the UnresolvedTypes list as well.
510 TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
511 Ty);
512 if (TI != TypeStack.end()) {
513 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
514 if (I == UnresolvedTypes.end()) {
515 Out << "PATypeHolder " << typeName;
516 Out << "_fwd = OpaqueType::get(mod->getContext());";
517 nl(Out);
518 UnresolvedTypes[Ty] = typeName;
519 }
520 return true;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000521 }
522
Chris Lattner7e6d7452010-06-21 23:12:56 +0000523 // We're going to print a derived type which, by definition, contains other
524 // types. So, push this one we're printing onto the type stack to assist with
525 // recursive definitions.
526 TypeStack.push_back(Ty);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000527
Chris Lattner7e6d7452010-06-21 23:12:56 +0000528 // Print the type definition
529 switch (Ty->getTypeID()) {
530 case Type::FunctionTyID: {
531 const FunctionType* FT = cast<FunctionType>(Ty);
532 Out << "std::vector<const Type*>" << typeName << "_args;";
533 nl(Out);
534 FunctionType::param_iterator PI = FT->param_begin();
535 FunctionType::param_iterator PE = FT->param_end();
536 for (; PI != PE; ++PI) {
537 const Type* argTy = static_cast<const Type*>(*PI);
538 bool isForward = printTypeInternal(argTy);
539 std::string argName(getCppName(argTy));
540 Out << typeName << "_args.push_back(" << argName;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000541 if (isForward)
542 Out << "_fwd";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000543 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000544 nl(Out);
545 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000546 bool isForward = printTypeInternal(FT->getReturnType());
547 std::string retTypeName(getCppName(FT->getReturnType()));
548 Out << "FunctionType* " << typeName << " = FunctionType::get(";
549 in(); nl(Out) << "/*Result=*/" << retTypeName;
550 if (isForward)
551 Out << "_fwd";
552 Out << ",";
553 nl(Out) << "/*Params=*/" << typeName << "_args,";
554 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
555 out();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000556 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000557 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000558 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000559 case Type::StructTyID: {
560 const StructType* ST = cast<StructType>(Ty);
561 Out << "std::vector<const Type*>" << typeName << "_fields;";
562 nl(Out);
563 StructType::element_iterator EI = ST->element_begin();
564 StructType::element_iterator EE = ST->element_end();
565 for (; EI != EE; ++EI) {
566 const Type* fieldTy = static_cast<const Type*>(*EI);
567 bool isForward = printTypeInternal(fieldTy);
568 std::string fieldName(getCppName(fieldTy));
569 Out << typeName << "_fields.push_back(" << fieldName;
570 if (isForward)
571 Out << "_fwd";
572 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000573 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000574 }
575 Out << "StructType* " << typeName << " = StructType::get("
576 << "mod->getContext(), "
577 << typeName << "_fields, /*isPacked=*/"
578 << (ST->isPacked() ? "true" : "false") << ");";
579 nl(Out);
580 break;
581 }
582 case Type::ArrayTyID: {
583 const ArrayType* AT = cast<ArrayType>(Ty);
584 const Type* ET = AT->getElementType();
585 bool isForward = printTypeInternal(ET);
586 std::string elemName(getCppName(ET));
587 Out << "ArrayType* " << typeName << " = ArrayType::get("
588 << elemName << (isForward ? "_fwd" : "")
589 << ", " << utostr(AT->getNumElements()) << ");";
590 nl(Out);
591 break;
592 }
593 case Type::PointerTyID: {
594 const PointerType* PT = cast<PointerType>(Ty);
595 const Type* ET = PT->getElementType();
596 bool isForward = printTypeInternal(ET);
597 std::string elemName(getCppName(ET));
598 Out << "PointerType* " << typeName << " = PointerType::get("
599 << elemName << (isForward ? "_fwd" : "")
600 << ", " << utostr(PT->getAddressSpace()) << ");";
601 nl(Out);
602 break;
603 }
604 case Type::VectorTyID: {
605 const VectorType* PT = cast<VectorType>(Ty);
606 const Type* ET = PT->getElementType();
607 bool isForward = printTypeInternal(ET);
608 std::string elemName(getCppName(ET));
609 Out << "VectorType* " << typeName << " = VectorType::get("
610 << elemName << (isForward ? "_fwd" : "")
611 << ", " << utostr(PT->getNumElements()) << ");";
612 nl(Out);
613 break;
614 }
615 case Type::OpaqueTyID: {
616 Out << "OpaqueType* " << typeName;
617 Out << " = OpaqueType::get(mod->getContext());";
618 nl(Out);
619 break;
620 }
621 default:
622 error("Invalid TypeID");
623 }
624
625 // If the type had a name, make sure we recreate it.
626 const std::string* progTypeName =
627 findTypeName(TheModule->getTypeSymbolTable(),Ty);
628 if (progTypeName) {
629 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
630 << typeName << ");";
631 nl(Out);
632 }
633
634 // Pop us off the type stack
635 TypeStack.pop_back();
636
637 // Indicate that this type is now defined.
638 DefinedTypes.insert(Ty);
639
640 // Early resolve as many unresolved types as possible. Search the unresolved
641 // types map for the type we just printed. Now that its definition is complete
642 // we can resolve any previous references to it. This prevents a cascade of
643 // unresolved types.
644 TypeMap::iterator I = UnresolvedTypes.find(Ty);
645 if (I != UnresolvedTypes.end()) {
646 Out << "cast<OpaqueType>(" << I->second
647 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
648 nl(Out);
649 Out << I->second << " = cast<";
650 switch (Ty->getTypeID()) {
651 case Type::FunctionTyID: Out << "FunctionType"; break;
652 case Type::ArrayTyID: Out << "ArrayType"; break;
653 case Type::StructTyID: Out << "StructType"; break;
654 case Type::VectorTyID: Out << "VectorType"; break;
655 case Type::PointerTyID: Out << "PointerType"; break;
656 case Type::OpaqueTyID: Out << "OpaqueType"; break;
657 default: Out << "NoSuchDerivedType"; break;
658 }
659 Out << ">(" << I->second << "_fwd.get());";
660 nl(Out); nl(Out);
661 UnresolvedTypes.erase(I);
662 }
663
664 // Finally, separate the type definition from other with a newline.
665 nl(Out);
666
667 // We weren't a recursive type
668 return false;
669}
670
671// Prints a type definition. Returns true if it could not resolve all the
672// types in the definition but had to use a forward reference.
673void CppWriter::printType(const Type* Ty) {
674 assert(TypeStack.empty());
675 TypeStack.clear();
676 printTypeInternal(Ty);
677 assert(TypeStack.empty());
678}
679
680void CppWriter::printTypes(const Module* M) {
681 // Walk the symbol table and print out all its types
682 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
683 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
684 TI != TE; ++TI) {
685
686 // For primitive types and types already defined, just add a name
687 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
688 if (TI->second->isIntegerTy() || TI->second->isPrimitiveType() ||
689 TNI != TypeNames.end()) {
690 Out << "mod->addTypeName(\"";
691 printEscapedString(TI->first);
692 Out << "\", " << getCppName(TI->second) << ");";
693 nl(Out);
694 // For everything else, define the type
695 } else {
696 printType(TI->second);
697 }
698 }
699
700 // Add all of the global variables to the value table...
701 for (Module::const_global_iterator I = TheModule->global_begin(),
702 E = TheModule->global_end(); I != E; ++I) {
703 if (I->hasInitializer())
704 printType(I->getInitializer()->getType());
705 printType(I->getType());
706 }
707
708 // Add all the functions to the table
709 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
710 FI != FE; ++FI) {
711 printType(FI->getReturnType());
712 printType(FI->getFunctionType());
713 // Add all the function arguments
714 for (Function::const_arg_iterator AI = FI->arg_begin(),
715 AE = FI->arg_end(); AI != AE; ++AI) {
716 printType(AI->getType());
717 }
718
719 // Add all of the basic blocks and instructions
720 for (Function::const_iterator BB = FI->begin(),
721 E = FI->end(); BB != E; ++BB) {
722 printType(BB->getType());
723 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
724 ++I) {
725 printType(I->getType());
726 for (unsigned i = 0; i < I->getNumOperands(); ++i)
727 printType(I->getOperand(i)->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000728 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000729 }
730 }
731}
732
733
734// printConstant - Print out a constant pool entry...
735void CppWriter::printConstant(const Constant *CV) {
736 // First, if the constant is actually a GlobalValue (variable or function)
737 // or its already in the constant list then we've printed it already and we
738 // can just return.
739 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
740 return;
741
742 std::string constName(getCppName(CV));
743 std::string typeName(getCppName(CV->getType()));
744
745 if (isa<GlobalValue>(CV)) {
746 // Skip variables and functions, we emit them elsewhere
747 return;
748 }
749
750 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
751 std::string constValue = CI->getValue().toString(10, true);
752 Out << "ConstantInt* " << constName
753 << " = ConstantInt::get(mod->getContext(), APInt("
754 << cast<IntegerType>(CI->getType())->getBitWidth()
755 << ", StringRef(\"" << constValue << "\"), 10));";
756 } else if (isa<ConstantAggregateZero>(CV)) {
757 Out << "ConstantAggregateZero* " << constName
758 << " = ConstantAggregateZero::get(" << typeName << ");";
759 } else if (isa<ConstantPointerNull>(CV)) {
760 Out << "ConstantPointerNull* " << constName
761 << " = ConstantPointerNull::get(" << typeName << ");";
762 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
763 Out << "ConstantFP* " << constName << " = ";
764 printCFP(CFP);
765 Out << ";";
766 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
767 if (CA->isString() &&
768 CA->getType()->getElementType() ==
769 Type::getInt8Ty(CA->getContext())) {
770 Out << "Constant* " << constName <<
771 " = ConstantArray::get(mod->getContext(), \"";
772 std::string tmp = CA->getAsString();
773 bool nullTerminate = false;
774 if (tmp[tmp.length()-1] == 0) {
775 tmp.erase(tmp.length()-1);
776 nullTerminate = true;
777 }
778 printEscapedString(tmp);
779 // Determine if we want null termination or not.
780 if (nullTerminate)
781 Out << "\", true"; // Indicate that the null terminator should be
782 // added.
783 else
784 Out << "\", false";// No null terminator
785 Out << ");";
786 } else {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000787 Out << "std::vector<Constant*> " << constName << "_elems;";
788 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +0000789 unsigned N = CA->getNumOperands();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000790 for (unsigned i = 0; i < N; ++i) {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000791 printConstant(CA->getOperand(i)); // recurse to print operands
Anton Korobeynikov50276522008-04-23 22:29:24 +0000792 Out << constName << "_elems.push_back("
Chris Lattner7e6d7452010-06-21 23:12:56 +0000793 << getCppName(CA->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000794 nl(Out);
795 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000796 Out << "Constant* " << constName << " = ConstantArray::get("
Anton Korobeynikov50276522008-04-23 22:29:24 +0000797 << typeName << ", " << constName << "_elems);";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000798 }
799 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
800 Out << "std::vector<Constant*> " << constName << "_fields;";
801 nl(Out);
802 unsigned N = CS->getNumOperands();
803 for (unsigned i = 0; i < N; i++) {
804 printConstant(CS->getOperand(i));
805 Out << constName << "_fields.push_back("
806 << getCppName(CS->getOperand(i)) << ");";
807 nl(Out);
808 }
809 Out << "Constant* " << constName << " = ConstantStruct::get("
810 << typeName << ", " << constName << "_fields);";
811 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
812 Out << "std::vector<Constant*> " << constName << "_elems;";
813 nl(Out);
814 unsigned N = CP->getNumOperands();
815 for (unsigned i = 0; i < N; ++i) {
816 printConstant(CP->getOperand(i));
817 Out << constName << "_elems.push_back("
818 << getCppName(CP->getOperand(i)) << ");";
819 nl(Out);
820 }
821 Out << "Constant* " << constName << " = ConstantVector::get("
822 << typeName << ", " << constName << "_elems);";
823 } else if (isa<UndefValue>(CV)) {
824 Out << "UndefValue* " << constName << " = UndefValue::get("
825 << typeName << ");";
826 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
827 if (CE->getOpcode() == Instruction::GetElementPtr) {
828 Out << "std::vector<Constant*> " << constName << "_indices;";
829 nl(Out);
830 printConstant(CE->getOperand(0));
831 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
832 printConstant(CE->getOperand(i));
833 Out << constName << "_indices.push_back("
834 << getCppName(CE->getOperand(i)) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000835 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000836 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000837 Out << "Constant* " << constName
838 << " = ConstantExpr::getGetElementPtr("
839 << getCppName(CE->getOperand(0)) << ", "
840 << "&" << constName << "_indices[0], "
841 << constName << "_indices.size()"
842 << ");";
843 } else if (CE->isCast()) {
844 printConstant(CE->getOperand(0));
845 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
846 switch (CE->getOpcode()) {
847 default: llvm_unreachable("Invalid cast opcode");
848 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
849 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
850 case Instruction::SExt: Out << "Instruction::SExt"; break;
851 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
852 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
853 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
854 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
855 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
856 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
857 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
858 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
859 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
860 }
861 Out << ", " << getCppName(CE->getOperand(0)) << ", "
862 << getCppName(CE->getType()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000863 } else {
Chris Lattner7e6d7452010-06-21 23:12:56 +0000864 unsigned N = CE->getNumOperands();
865 for (unsigned i = 0; i < N; ++i ) {
866 printConstant(CE->getOperand(i));
867 }
868 Out << "Constant* " << constName << " = ConstantExpr::";
869 switch (CE->getOpcode()) {
870 case Instruction::Add: Out << "getAdd("; break;
871 case Instruction::FAdd: Out << "getFAdd("; break;
872 case Instruction::Sub: Out << "getSub("; break;
873 case Instruction::FSub: Out << "getFSub("; break;
874 case Instruction::Mul: Out << "getMul("; break;
875 case Instruction::FMul: Out << "getFMul("; break;
876 case Instruction::UDiv: Out << "getUDiv("; break;
877 case Instruction::SDiv: Out << "getSDiv("; break;
878 case Instruction::FDiv: Out << "getFDiv("; break;
879 case Instruction::URem: Out << "getURem("; break;
880 case Instruction::SRem: Out << "getSRem("; break;
881 case Instruction::FRem: Out << "getFRem("; break;
882 case Instruction::And: Out << "getAnd("; break;
883 case Instruction::Or: Out << "getOr("; break;
884 case Instruction::Xor: Out << "getXor("; break;
885 case Instruction::ICmp:
886 Out << "getICmp(ICmpInst::ICMP_";
887 switch (CE->getPredicate()) {
888 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
889 case ICmpInst::ICMP_NE: Out << "NE"; break;
890 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
891 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
892 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
893 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
894 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
895 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
896 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
897 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
898 default: error("Invalid ICmp Predicate");
899 }
900 break;
901 case Instruction::FCmp:
902 Out << "getFCmp(FCmpInst::FCMP_";
903 switch (CE->getPredicate()) {
904 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
905 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
906 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
907 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
908 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
909 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
910 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
911 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
912 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
913 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
914 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
915 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
916 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
917 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
918 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
919 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
920 default: error("Invalid FCmp Predicate");
921 }
922 break;
923 case Instruction::Shl: Out << "getShl("; break;
924 case Instruction::LShr: Out << "getLShr("; break;
925 case Instruction::AShr: Out << "getAShr("; break;
926 case Instruction::Select: Out << "getSelect("; break;
927 case Instruction::ExtractElement: Out << "getExtractElement("; break;
928 case Instruction::InsertElement: Out << "getInsertElement("; break;
929 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
930 default:
931 error("Invalid constant expression");
932 break;
933 }
934 Out << getCppName(CE->getOperand(0));
935 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
936 Out << ", " << getCppName(CE->getOperand(i));
937 Out << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000938 }
Chris Lattner32848772010-06-21 23:19:36 +0000939 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
940 Out << "Constant* " << constName << " = ";
941 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
Chris Lattner7e6d7452010-06-21 23:12:56 +0000942 } else {
943 error("Bad Constant");
944 Out << "Constant* " << constName << " = 0; ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000945 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000946 nl(Out);
947}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000948
Chris Lattner7e6d7452010-06-21 23:12:56 +0000949void CppWriter::printConstants(const Module* M) {
950 // Traverse all the global variables looking for constant initializers
951 for (Module::const_global_iterator I = TheModule->global_begin(),
952 E = TheModule->global_end(); I != E; ++I)
953 if (I->hasInitializer())
954 printConstant(I->getInitializer());
Anton Korobeynikov50276522008-04-23 22:29:24 +0000955
Chris Lattner7e6d7452010-06-21 23:12:56 +0000956 // Traverse the LLVM functions looking for constants
957 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
958 FI != FE; ++FI) {
959 // Add all of the basic blocks and instructions
960 for (Function::const_iterator BB = FI->begin(),
961 E = FI->end(); BB != E; ++BB) {
962 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
963 ++I) {
964 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
965 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
966 printConstant(C);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000967 }
968 }
969 }
970 }
971 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000972}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000973
Chris Lattner7e6d7452010-06-21 23:12:56 +0000974void CppWriter::printVariableUses(const GlobalVariable *GV) {
975 nl(Out) << "// Type Definitions";
976 nl(Out);
977 printType(GV->getType());
978 if (GV->hasInitializer()) {
979 Constant *Init = GV->getInitializer();
980 printType(Init->getType());
981 if (Function *F = dyn_cast<Function>(Init)) {
982 nl(Out)<< "/ Function Declarations"; nl(Out);
983 printFunctionHead(F);
984 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
985 nl(Out) << "// Global Variable Declarations"; nl(Out);
986 printVariableHead(gv);
987
988 nl(Out) << "// Global Variable Definitions"; nl(Out);
989 printVariableBody(gv);
990 } else {
991 nl(Out) << "// Constant Definitions"; nl(Out);
992 printConstant(Init);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000993 }
994 }
Chris Lattner7e6d7452010-06-21 23:12:56 +0000995}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000996
Chris Lattner7e6d7452010-06-21 23:12:56 +0000997void CppWriter::printVariableHead(const GlobalVariable *GV) {
998 nl(Out) << "GlobalVariable* " << getCppName(GV);
999 if (is_inline) {
1000 Out << " = mod->getGlobalVariable(mod->getContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001001 printEscapedString(GV->getName());
Chris Lattner7e6d7452010-06-21 23:12:56 +00001002 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
1003 nl(Out) << "if (!" << getCppName(GV) << ") {";
1004 in(); nl(Out) << getCppName(GV);
1005 }
1006 Out << " = new GlobalVariable(/*Module=*/*mod, ";
1007 nl(Out) << "/*Type=*/";
1008 printCppName(GV->getType()->getElementType());
1009 Out << ",";
1010 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1011 Out << ",";
1012 nl(Out) << "/*Linkage=*/";
1013 printLinkageType(GV->getLinkage());
1014 Out << ",";
1015 nl(Out) << "/*Initializer=*/0, ";
1016 if (GV->hasInitializer()) {
1017 Out << "// has initializer, specified below";
1018 }
1019 nl(Out) << "/*Name=*/\"";
1020 printEscapedString(GV->getName());
1021 Out << "\");";
1022 nl(Out);
1023
1024 if (GV->hasSection()) {
1025 printCppName(GV);
1026 Out << "->setSection(\"";
1027 printEscapedString(GV->getSection());
Owen Anderson16a412e2009-07-10 16:42:19 +00001028 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001029 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001030 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001031 if (GV->getAlignment()) {
1032 printCppName(GV);
1033 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001034 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001035 }
1036 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1037 printCppName(GV);
1038 Out << "->setVisibility(";
1039 printVisibilityType(GV->getVisibility());
1040 Out << ");";
1041 nl(Out);
1042 }
1043 if (GV->isThreadLocal()) {
1044 printCppName(GV);
1045 Out << "->setThreadLocal(true);";
1046 nl(Out);
1047 }
1048 if (is_inline) {
1049 out(); Out << "}"; nl(Out);
1050 }
1051}
1052
1053void CppWriter::printVariableBody(const GlobalVariable *GV) {
1054 if (GV->hasInitializer()) {
1055 printCppName(GV);
1056 Out << "->setInitializer(";
1057 Out << getCppName(GV->getInitializer()) << ");";
1058 nl(Out);
1059 }
1060}
1061
1062std::string CppWriter::getOpName(Value* V) {
1063 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1064 return getCppName(V);
1065
1066 // See if its alread in the map of forward references, if so just return the
1067 // name we already set up for it
1068 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1069 if (I != ForwardRefs.end())
1070 return I->second;
1071
1072 // This is a new forward reference. Generate a unique name for it
1073 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1074
1075 // Yes, this is a hack. An Argument is the smallest instantiable value that
1076 // we can make as a placeholder for the real value. We'll replace these
1077 // Argument instances later.
1078 Out << "Argument* " << result << " = new Argument("
1079 << getCppName(V->getType()) << ");";
1080 nl(Out);
1081 ForwardRefs[V] = result;
1082 return result;
1083}
1084
1085// printInstruction - This member is called for each Instruction in a function.
1086void CppWriter::printInstruction(const Instruction *I,
1087 const std::string& bbname) {
1088 std::string iName(getCppName(I));
1089
1090 // Before we emit this instruction, we need to take care of generating any
1091 // forward references. So, we get the names of all the operands in advance
1092 const unsigned Ops(I->getNumOperands());
1093 std::string* opNames = new std::string[Ops];
Chris Lattner32848772010-06-21 23:19:36 +00001094 for (unsigned i = 0; i < Ops; i++)
Chris Lattner7e6d7452010-06-21 23:12:56 +00001095 opNames[i] = getOpName(I->getOperand(i));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001096
Chris Lattner7e6d7452010-06-21 23:12:56 +00001097 switch (I->getOpcode()) {
1098 default:
1099 error("Invalid instruction");
1100 break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001101
Chris Lattner7e6d7452010-06-21 23:12:56 +00001102 case Instruction::Ret: {
1103 const ReturnInst* ret = cast<ReturnInst>(I);
1104 Out << "ReturnInst::Create(mod->getContext(), "
1105 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1106 break;
1107 }
1108 case Instruction::Br: {
1109 const BranchInst* br = cast<BranchInst>(I);
1110 Out << "BranchInst::Create(" ;
Chris Lattner32848772010-06-21 23:19:36 +00001111 if (br->getNumOperands() == 3) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001112 Out << opNames[2] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001113 << opNames[1] << ", "
Chris Lattner7e6d7452010-06-21 23:12:56 +00001114 << opNames[0] << ", ";
1115
1116 } else if (br->getNumOperands() == 1) {
1117 Out << opNames[0] << ", ";
1118 } else {
1119 error("Branch with 2 operands?");
1120 }
1121 Out << bbname << ");";
1122 break;
1123 }
1124 case Instruction::Switch: {
1125 const SwitchInst *SI = cast<SwitchInst>(I);
1126 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1127 << opNames[0] << ", "
1128 << opNames[1] << ", "
1129 << SI->getNumCases() << ", " << bbname << ");";
1130 nl(Out);
1131 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
1132 Out << iName << "->addCase("
1133 << opNames[i] << ", "
1134 << opNames[i+1] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001135 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001136 }
1137 break;
1138 }
1139 case Instruction::IndirectBr: {
1140 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1141 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
1142 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1143 nl(Out);
1144 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1145 Out << iName << "->addDestination(" << opNames[i] << ");";
1146 nl(Out);
1147 }
1148 break;
1149 }
1150 case Instruction::Invoke: {
1151 const InvokeInst* inv = cast<InvokeInst>(I);
1152 Out << "std::vector<Value*> " << iName << "_params;";
1153 nl(Out);
1154 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1155 Out << iName << "_params.push_back("
1156 << getOpName(inv->getArgOperand(i)) << ");";
1157 nl(Out);
1158 }
1159 // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1160 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1161 << getOpName(inv->getCalledFunction()) << ", "
1162 << getOpName(inv->getNormalDest()) << ", "
1163 << getOpName(inv->getUnwindDest()) << ", "
1164 << iName << "_params.begin(), "
1165 << iName << "_params.end(), \"";
1166 printEscapedString(inv->getName());
1167 Out << "\", " << bbname << ");";
1168 nl(Out) << iName << "->setCallingConv(";
1169 printCallingConv(inv->getCallingConv());
1170 Out << ");";
1171 printAttributes(inv->getAttributes(), iName);
1172 Out << iName << "->setAttributes(" << iName << "_PAL);";
1173 nl(Out);
1174 break;
1175 }
1176 case Instruction::Unwind: {
1177 Out << "new UnwindInst("
1178 << bbname << ");";
1179 break;
1180 }
1181 case Instruction::Unreachable: {
1182 Out << "new UnreachableInst("
1183 << "mod->getContext(), "
1184 << bbname << ");";
1185 break;
1186 }
1187 case Instruction::Add:
1188 case Instruction::FAdd:
1189 case Instruction::Sub:
1190 case Instruction::FSub:
1191 case Instruction::Mul:
1192 case Instruction::FMul:
1193 case Instruction::UDiv:
1194 case Instruction::SDiv:
1195 case Instruction::FDiv:
1196 case Instruction::URem:
1197 case Instruction::SRem:
1198 case Instruction::FRem:
1199 case Instruction::And:
1200 case Instruction::Or:
1201 case Instruction::Xor:
1202 case Instruction::Shl:
1203 case Instruction::LShr:
1204 case Instruction::AShr:{
1205 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1206 switch (I->getOpcode()) {
1207 case Instruction::Add: Out << "Instruction::Add"; break;
1208 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1209 case Instruction::Sub: Out << "Instruction::Sub"; break;
1210 case Instruction::FSub: Out << "Instruction::FSub"; break;
1211 case Instruction::Mul: Out << "Instruction::Mul"; break;
1212 case Instruction::FMul: Out << "Instruction::FMul"; break;
1213 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1214 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1215 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1216 case Instruction::URem:Out << "Instruction::URem"; break;
1217 case Instruction::SRem:Out << "Instruction::SRem"; break;
1218 case Instruction::FRem:Out << "Instruction::FRem"; break;
1219 case Instruction::And: Out << "Instruction::And"; break;
1220 case Instruction::Or: Out << "Instruction::Or"; break;
1221 case Instruction::Xor: Out << "Instruction::Xor"; break;
1222 case Instruction::Shl: Out << "Instruction::Shl"; break;
1223 case Instruction::LShr:Out << "Instruction::LShr"; break;
1224 case Instruction::AShr:Out << "Instruction::AShr"; break;
1225 default: Out << "Instruction::BadOpCode"; break;
1226 }
1227 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1228 printEscapedString(I->getName());
1229 Out << "\", " << bbname << ");";
1230 break;
1231 }
1232 case Instruction::FCmp: {
1233 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1234 switch (cast<FCmpInst>(I)->getPredicate()) {
1235 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1236 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1237 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1238 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1239 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1240 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1241 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1242 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1243 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1244 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1245 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1246 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1247 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1248 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1249 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1250 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1251 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1252 }
1253 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1254 printEscapedString(I->getName());
1255 Out << "\");";
1256 break;
1257 }
1258 case Instruction::ICmp: {
1259 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1260 switch (cast<ICmpInst>(I)->getPredicate()) {
1261 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1262 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1263 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1264 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1265 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1266 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1267 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1268 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1269 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1270 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1271 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1272 }
1273 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1274 printEscapedString(I->getName());
1275 Out << "\");";
1276 break;
1277 }
1278 case Instruction::Alloca: {
1279 const AllocaInst* allocaI = cast<AllocaInst>(I);
1280 Out << "AllocaInst* " << iName << " = new AllocaInst("
1281 << getCppName(allocaI->getAllocatedType()) << ", ";
1282 if (allocaI->isArrayAllocation())
1283 Out << opNames[0] << ", ";
1284 Out << "\"";
1285 printEscapedString(allocaI->getName());
1286 Out << "\", " << bbname << ");";
1287 if (allocaI->getAlignment())
1288 nl(Out) << iName << "->setAlignment("
1289 << allocaI->getAlignment() << ");";
1290 break;
1291 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001292 case Instruction::Load: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001293 const LoadInst* load = cast<LoadInst>(I);
1294 Out << "LoadInst* " << iName << " = new LoadInst("
1295 << opNames[0] << ", \"";
1296 printEscapedString(load->getName());
1297 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1298 << ", " << bbname << ");";
1299 break;
1300 }
1301 case Instruction::Store: {
1302 const StoreInst* store = cast<StoreInst>(I);
1303 Out << " new StoreInst("
1304 << opNames[0] << ", "
1305 << opNames[1] << ", "
1306 << (store->isVolatile() ? "true" : "false")
1307 << ", " << bbname << ");";
1308 break;
1309 }
1310 case Instruction::GetElementPtr: {
1311 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1312 if (gep->getNumOperands() <= 2) {
1313 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1314 << opNames[0];
1315 if (gep->getNumOperands() == 2)
1316 Out << ", " << opNames[1];
1317 } else {
1318 Out << "std::vector<Value*> " << iName << "_indices;";
1319 nl(Out);
1320 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1321 Out << iName << "_indices.push_back("
1322 << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001323 nl(Out);
1324 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001325 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1326 << opNames[0] << ", " << iName << "_indices.begin(), "
1327 << iName << "_indices.end()";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001328 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001329 Out << ", \"";
1330 printEscapedString(gep->getName());
1331 Out << "\", " << bbname << ");";
1332 break;
1333 }
1334 case Instruction::PHI: {
1335 const PHINode* phi = cast<PHINode>(I);
1336
1337 Out << "PHINode* " << iName << " = PHINode::Create("
1338 << getCppName(phi->getType()) << ", \"";
1339 printEscapedString(phi->getName());
1340 Out << "\", " << bbname << ");";
1341 nl(Out) << iName << "->reserveOperandSpace("
1342 << phi->getNumIncomingValues()
1343 << ");";
1344 nl(Out);
1345 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1346 Out << iName << "->addIncoming("
1347 << opNames[i] << ", " << opNames[i+1] << ");";
Chris Lattner627b4702009-10-27 21:24:48 +00001348 nl(Out);
Chris Lattner627b4702009-10-27 21:24:48 +00001349 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001350 break;
1351 }
1352 case Instruction::Trunc:
1353 case Instruction::ZExt:
1354 case Instruction::SExt:
1355 case Instruction::FPTrunc:
1356 case Instruction::FPExt:
1357 case Instruction::FPToUI:
1358 case Instruction::FPToSI:
1359 case Instruction::UIToFP:
1360 case Instruction::SIToFP:
1361 case Instruction::PtrToInt:
1362 case Instruction::IntToPtr:
1363 case Instruction::BitCast: {
1364 const CastInst* cst = cast<CastInst>(I);
1365 Out << "CastInst* " << iName << " = new ";
1366 switch (I->getOpcode()) {
1367 case Instruction::Trunc: Out << "TruncInst"; break;
1368 case Instruction::ZExt: Out << "ZExtInst"; break;
1369 case Instruction::SExt: Out << "SExtInst"; break;
1370 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1371 case Instruction::FPExt: Out << "FPExtInst"; break;
1372 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1373 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1374 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1375 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1376 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1377 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1378 case Instruction::BitCast: Out << "BitCastInst"; break;
1379 default: assert(!"Unreachable"); break;
1380 }
1381 Out << "(" << opNames[0] << ", "
1382 << getCppName(cst->getType()) << ", \"";
1383 printEscapedString(cst->getName());
1384 Out << "\", " << bbname << ");";
1385 break;
1386 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001387 case Instruction::Call: {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001388 const CallInst* call = cast<CallInst>(I);
1389 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1390 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1391 << getCppName(ila->getFunctionType()) << ", \""
1392 << ila->getAsmString() << "\", \""
1393 << ila->getConstraintString() << "\","
1394 << (ila->hasSideEffects() ? "true" : "false") << ");";
1395 nl(Out);
1396 }
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001397 if (call->getNumArgOperands() > 1) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001398 Out << "std::vector<Value*> " << iName << "_params;";
1399 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001400 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1401 Out << iName << "_params.push_back(" << opNames[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001402 nl(Out);
1403 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001404 Out << "CallInst* " << iName << " = CallInst::Create("
1405 << opNames[0] << ", " << iName << "_params.begin(), "
Bill Wendling22a5b292010-06-07 19:05:06 +00001406 << iName << "_params.end(), \"";
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001407 } else if (call->getNumArgOperands() == 1) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001408 Out << "CallInst* " << iName << " = CallInst::Create("
1409 << opNames[0] << ", " << opNames[1] << ", \"";
1410 } else {
1411 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1412 << ", \"";
1413 }
1414 printEscapedString(call->getName());
1415 Out << "\", " << bbname << ");";
1416 nl(Out) << iName << "->setCallingConv(";
1417 printCallingConv(call->getCallingConv());
1418 Out << ");";
1419 nl(Out) << iName << "->setTailCall("
Gabor Greif7a1d92a2010-06-26 12:17:21 +00001420 << (call->isTailCall() ? "true" : "false");
Chris Lattner7e6d7452010-06-21 23:12:56 +00001421 Out << ");";
1422 printAttributes(call->getAttributes(), iName);
1423 Out << iName << "->setAttributes(" << iName << "_PAL);";
1424 nl(Out);
1425 break;
1426 }
1427 case Instruction::Select: {
1428 const SelectInst* sel = cast<SelectInst>(I);
1429 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1430 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1431 printEscapedString(sel->getName());
1432 Out << "\", " << bbname << ");";
1433 break;
1434 }
1435 case Instruction::UserOp1:
1436 /// FALL THROUGH
1437 case Instruction::UserOp2: {
1438 /// FIXME: What should be done here?
1439 break;
1440 }
1441 case Instruction::VAArg: {
1442 const VAArgInst* va = cast<VAArgInst>(I);
1443 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1444 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1445 printEscapedString(va->getName());
1446 Out << "\", " << bbname << ");";
1447 break;
1448 }
1449 case Instruction::ExtractElement: {
1450 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1451 Out << "ExtractElementInst* " << getCppName(eei)
1452 << " = new ExtractElementInst(" << opNames[0]
1453 << ", " << opNames[1] << ", \"";
1454 printEscapedString(eei->getName());
1455 Out << "\", " << bbname << ");";
1456 break;
1457 }
1458 case Instruction::InsertElement: {
1459 const InsertElementInst* iei = cast<InsertElementInst>(I);
1460 Out << "InsertElementInst* " << getCppName(iei)
1461 << " = InsertElementInst::Create(" << opNames[0]
1462 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1463 printEscapedString(iei->getName());
1464 Out << "\", " << bbname << ");";
1465 break;
1466 }
1467 case Instruction::ShuffleVector: {
1468 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1469 Out << "ShuffleVectorInst* " << getCppName(svi)
1470 << " = new ShuffleVectorInst(" << opNames[0]
1471 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1472 printEscapedString(svi->getName());
1473 Out << "\", " << bbname << ");";
1474 break;
1475 }
1476 case Instruction::ExtractValue: {
1477 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1478 Out << "std::vector<unsigned> " << iName << "_indices;";
1479 nl(Out);
1480 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1481 Out << iName << "_indices.push_back("
1482 << evi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001483 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001484 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001485 Out << "ExtractValueInst* " << getCppName(evi)
1486 << " = ExtractValueInst::Create(" << opNames[0]
1487 << ", "
1488 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1489 printEscapedString(evi->getName());
1490 Out << "\", " << bbname << ");";
1491 break;
1492 }
1493 case Instruction::InsertValue: {
1494 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1495 Out << "std::vector<unsigned> " << iName << "_indices;";
1496 nl(Out);
1497 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1498 Out << iName << "_indices.push_back("
1499 << ivi->idx_begin()[i] << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001500 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001501 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001502 Out << "InsertValueInst* " << getCppName(ivi)
1503 << " = InsertValueInst::Create(" << opNames[0]
1504 << ", " << opNames[1] << ", "
1505 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1506 printEscapedString(ivi->getName());
1507 Out << "\", " << bbname << ");";
1508 break;
1509 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001510 }
1511 DefinedValues.insert(I);
1512 nl(Out);
1513 delete [] opNames;
1514}
1515
Chris Lattner7e6d7452010-06-21 23:12:56 +00001516// Print out the types, constants and declarations needed by one function
1517void CppWriter::printFunctionUses(const Function* F) {
1518 nl(Out) << "// Type Definitions"; nl(Out);
1519 if (!is_inline) {
1520 // Print the function's return type
1521 printType(F->getReturnType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001522
Chris Lattner7e6d7452010-06-21 23:12:56 +00001523 // Print the function's function type
1524 printType(F->getFunctionType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001525
Chris Lattner7e6d7452010-06-21 23:12:56 +00001526 // Print the types of each of the function's arguments
Anton Korobeynikov50276522008-04-23 22:29:24 +00001527 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1528 AI != AE; ++AI) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001529 printType(AI->getType());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001530 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001531 }
1532
Chris Lattner7e6d7452010-06-21 23:12:56 +00001533 // Print type definitions for every type referenced by an instruction and
1534 // make a note of any global values or constants that are referenced
1535 SmallPtrSet<GlobalValue*,64> gvs;
1536 SmallPtrSet<Constant*,64> consts;
1537 for (Function::const_iterator BB = F->begin(), BE = F->end();
1538 BB != BE; ++BB){
1539 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001540 I != E; ++I) {
Chris Lattner7e6d7452010-06-21 23:12:56 +00001541 // Print the type of the instruction itself
1542 printType(I->getType());
1543
1544 // Print the type of each of the instruction's operands
1545 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1546 Value* operand = I->getOperand(i);
1547 printType(operand->getType());
1548
1549 // If the operand references a GVal or Constant, make a note of it
1550 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1551 gvs.insert(GV);
1552 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1553 if (GVar->hasInitializer())
1554 consts.insert(GVar->getInitializer());
1555 } else if (Constant* C = dyn_cast<Constant>(operand))
1556 consts.insert(C);
1557 }
1558 }
1559 }
1560
1561 // Print the function declarations for any functions encountered
1562 nl(Out) << "// Function Declarations"; nl(Out);
1563 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1564 I != E; ++I) {
1565 if (Function* Fun = dyn_cast<Function>(*I)) {
1566 if (!is_inline || Fun != F)
1567 printFunctionHead(Fun);
1568 }
1569 }
1570
1571 // Print the global variable declarations for any variables encountered
1572 nl(Out) << "// Global Variable Declarations"; nl(Out);
1573 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1574 I != E; ++I) {
1575 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1576 printVariableHead(F);
1577 }
1578
1579// Print the constants found
1580 nl(Out) << "// Constant Definitions"; nl(Out);
1581 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1582 E = consts.end(); I != E; ++I) {
1583 printConstant(*I);
1584 }
1585
1586 // Process the global variables definitions now that all the constants have
1587 // been emitted. These definitions just couple the gvars with their constant
1588 // initializers.
1589 nl(Out) << "// Global Variable Definitions"; nl(Out);
1590 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1591 I != E; ++I) {
1592 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1593 printVariableBody(GV);
1594 }
1595}
1596
1597void CppWriter::printFunctionHead(const Function* F) {
1598 nl(Out) << "Function* " << getCppName(F);
1599 if (is_inline) {
1600 Out << " = mod->getFunction(\"";
1601 printEscapedString(F->getName());
1602 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1603 nl(Out) << "if (!" << getCppName(F) << ") {";
1604 nl(Out) << getCppName(F);
1605 }
1606 Out<< " = Function::Create(";
1607 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1608 nl(Out) << "/*Linkage=*/";
1609 printLinkageType(F->getLinkage());
1610 Out << ",";
1611 nl(Out) << "/*Name=*/\"";
1612 printEscapedString(F->getName());
1613 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1614 nl(Out,-1);
1615 printCppName(F);
1616 Out << "->setCallingConv(";
1617 printCallingConv(F->getCallingConv());
1618 Out << ");";
1619 nl(Out);
1620 if (F->hasSection()) {
1621 printCppName(F);
1622 Out << "->setSection(\"" << F->getSection() << "\");";
1623 nl(Out);
1624 }
1625 if (F->getAlignment()) {
1626 printCppName(F);
1627 Out << "->setAlignment(" << F->getAlignment() << ");";
1628 nl(Out);
1629 }
1630 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1631 printCppName(F);
1632 Out << "->setVisibility(";
1633 printVisibilityType(F->getVisibility());
1634 Out << ");";
1635 nl(Out);
1636 }
1637 if (F->hasGC()) {
1638 printCppName(F);
1639 Out << "->setGC(\"" << F->getGC() << "\");";
1640 nl(Out);
1641 }
1642 if (is_inline) {
1643 Out << "}";
1644 nl(Out);
1645 }
1646 printAttributes(F->getAttributes(), getCppName(F));
1647 printCppName(F);
1648 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1649 nl(Out);
1650}
1651
1652void CppWriter::printFunctionBody(const Function *F) {
1653 if (F->isDeclaration())
1654 return; // external functions have no bodies.
1655
1656 // Clear the DefinedValues and ForwardRefs maps because we can't have
1657 // cross-function forward refs
1658 ForwardRefs.clear();
1659 DefinedValues.clear();
1660
1661 // Create all the argument values
1662 if (!is_inline) {
1663 if (!F->arg_empty()) {
1664 Out << "Function::arg_iterator args = " << getCppName(F)
1665 << "->arg_begin();";
1666 nl(Out);
1667 }
1668 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1669 AI != AE; ++AI) {
1670 Out << "Value* " << getCppName(AI) << " = args++;";
1671 nl(Out);
1672 if (AI->hasName()) {
1673 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001674 nl(Out);
1675 }
1676 }
1677 }
1678
Chris Lattner7e6d7452010-06-21 23:12:56 +00001679 // Create all the basic blocks
1680 nl(Out);
1681 for (Function::const_iterator BI = F->begin(), BE = F->end();
1682 BI != BE; ++BI) {
1683 std::string bbname(getCppName(BI));
1684 Out << "BasicBlock* " << bbname <<
1685 " = BasicBlock::Create(mod->getContext(), \"";
1686 if (BI->hasName())
1687 printEscapedString(BI->getName());
1688 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1689 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001690 }
1691
Chris Lattner7e6d7452010-06-21 23:12:56 +00001692 // Output all of its basic blocks... for the function
1693 for (Function::const_iterator BI = F->begin(), BE = F->end();
1694 BI != BE; ++BI) {
1695 std::string bbname(getCppName(BI));
1696 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001697 nl(Out);
1698
Chris Lattner7e6d7452010-06-21 23:12:56 +00001699 // Output all of the instructions in the basic block...
1700 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1701 I != E; ++I) {
1702 printInstruction(I,bbname);
1703 }
1704 }
1705
1706 // Loop over the ForwardRefs and resolve them now that all instructions
1707 // are generated.
1708 if (!ForwardRefs.empty()) {
1709 nl(Out) << "// Resolve Forward References";
1710 nl(Out);
1711 }
1712
1713 while (!ForwardRefs.empty()) {
1714 ForwardRefMap::iterator I = ForwardRefs.begin();
1715 Out << I->second << "->replaceAllUsesWith("
1716 << getCppName(I->first) << "); delete " << I->second << ";";
1717 nl(Out);
1718 ForwardRefs.erase(I);
1719 }
1720}
1721
1722void CppWriter::printInline(const std::string& fname,
1723 const std::string& func) {
1724 const Function* F = TheModule->getFunction(func);
1725 if (!F) {
1726 error(std::string("Function '") + func + "' not found in input module");
1727 return;
1728 }
1729 if (F->isDeclaration()) {
1730 error(std::string("Function '") + func + "' is external!");
1731 return;
1732 }
1733 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1734 << getCppName(F);
1735 unsigned arg_count = 1;
1736 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1737 AI != AE; ++AI) {
1738 Out << ", Value* arg_" << arg_count;
1739 }
1740 Out << ") {";
1741 nl(Out);
1742 is_inline = true;
1743 printFunctionUses(F);
1744 printFunctionBody(F);
1745 is_inline = false;
1746 Out << "return " << getCppName(F->begin()) << ";";
1747 nl(Out) << "}";
1748 nl(Out);
1749}
1750
1751void CppWriter::printModuleBody() {
1752 // Print out all the type definitions
1753 nl(Out) << "// Type Definitions"; nl(Out);
1754 printTypes(TheModule);
1755
1756 // Functions can call each other and global variables can reference them so
1757 // define all the functions first before emitting their function bodies.
1758 nl(Out) << "// Function Declarations"; nl(Out);
1759 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1760 I != E; ++I)
1761 printFunctionHead(I);
1762
1763 // Process the global variables declarations. We can't initialze them until
1764 // after the constants are printed so just print a header for each global
1765 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1766 for (Module::const_global_iterator I = TheModule->global_begin(),
1767 E = TheModule->global_end(); I != E; ++I) {
1768 printVariableHead(I);
1769 }
1770
1771 // Print out all the constants definitions. Constants don't recurse except
1772 // through GlobalValues. All GlobalValues have been declared at this point
1773 // so we can proceed to generate the constants.
1774 nl(Out) << "// Constant Definitions"; nl(Out);
1775 printConstants(TheModule);
1776
1777 // Process the global variables definitions now that all the constants have
1778 // been emitted. These definitions just couple the gvars with their constant
1779 // initializers.
1780 nl(Out) << "// Global Variable Definitions"; nl(Out);
1781 for (Module::const_global_iterator I = TheModule->global_begin(),
1782 E = TheModule->global_end(); I != E; ++I) {
1783 printVariableBody(I);
1784 }
1785
1786 // Finally, we can safely put out all of the function bodies.
1787 nl(Out) << "// Function Definitions"; nl(Out);
1788 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1789 I != E; ++I) {
1790 if (!I->isDeclaration()) {
1791 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1792 << ")";
1793 nl(Out) << "{";
1794 nl(Out,1);
1795 printFunctionBody(I);
1796 nl(Out,-1) << "}";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001797 nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001798 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001799 }
1800}
1801
1802void CppWriter::printProgram(const std::string& fname,
1803 const std::string& mName) {
1804 Out << "#include <llvm/LLVMContext.h>\n";
1805 Out << "#include <llvm/Module.h>\n";
1806 Out << "#include <llvm/DerivedTypes.h>\n";
1807 Out << "#include <llvm/Constants.h>\n";
1808 Out << "#include <llvm/GlobalVariable.h>\n";
1809 Out << "#include <llvm/Function.h>\n";
1810 Out << "#include <llvm/CallingConv.h>\n";
1811 Out << "#include <llvm/BasicBlock.h>\n";
1812 Out << "#include <llvm/Instructions.h>\n";
1813 Out << "#include <llvm/InlineAsm.h>\n";
1814 Out << "#include <llvm/Support/FormattedStream.h>\n";
1815 Out << "#include <llvm/Support/MathExtras.h>\n";
1816 Out << "#include <llvm/Pass.h>\n";
1817 Out << "#include <llvm/PassManager.h>\n";
1818 Out << "#include <llvm/ADT/SmallVector.h>\n";
1819 Out << "#include <llvm/Analysis/Verifier.h>\n";
1820 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1821 Out << "#include <algorithm>\n";
1822 Out << "using namespace llvm;\n\n";
1823 Out << "Module* " << fname << "();\n\n";
1824 Out << "int main(int argc, char**argv) {\n";
1825 Out << " Module* Mod = " << fname << "();\n";
1826 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1827 Out << " PassManager PM;\n";
1828 Out << " PM.add(createPrintModulePass(&outs()));\n";
1829 Out << " PM.run(*Mod);\n";
1830 Out << " return 0;\n";
1831 Out << "}\n\n";
1832 printModule(fname,mName);
1833}
1834
1835void CppWriter::printModule(const std::string& fname,
1836 const std::string& mName) {
1837 nl(Out) << "Module* " << fname << "() {";
1838 nl(Out,1) << "// Module Construction";
1839 nl(Out) << "Module* mod = new Module(\"";
1840 printEscapedString(mName);
1841 Out << "\", getGlobalContext());";
1842 if (!TheModule->getTargetTriple().empty()) {
1843 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1844 }
1845 if (!TheModule->getTargetTriple().empty()) {
1846 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1847 << "\");";
1848 }
1849
1850 if (!TheModule->getModuleInlineAsm().empty()) {
1851 nl(Out) << "mod->setModuleInlineAsm(\"";
1852 printEscapedString(TheModule->getModuleInlineAsm());
1853 Out << "\");";
1854 }
1855 nl(Out);
1856
1857 // Loop over the dependent libraries and emit them.
1858 Module::lib_iterator LI = TheModule->lib_begin();
1859 Module::lib_iterator LE = TheModule->lib_end();
1860 while (LI != LE) {
1861 Out << "mod->addLibrary(\"" << *LI << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001862 nl(Out);
Chris Lattner7e6d7452010-06-21 23:12:56 +00001863 ++LI;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001864 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001865 printModuleBody();
1866 nl(Out) << "return mod;";
1867 nl(Out,-1) << "}";
1868 nl(Out);
1869}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001870
Chris Lattner7e6d7452010-06-21 23:12:56 +00001871void CppWriter::printContents(const std::string& fname,
1872 const std::string& mName) {
1873 Out << "\nModule* " << fname << "(Module *mod) {\n";
1874 Out << "\nmod->setModuleIdentifier(\"";
1875 printEscapedString(mName);
1876 Out << "\");\n";
1877 printModuleBody();
1878 Out << "\nreturn mod;\n";
1879 Out << "\n}\n";
1880}
1881
1882void CppWriter::printFunction(const std::string& fname,
1883 const std::string& funcName) {
1884 const Function* F = TheModule->getFunction(funcName);
1885 if (!F) {
1886 error(std::string("Function '") + funcName + "' not found in input module");
1887 return;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001888 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001889 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1890 printFunctionUses(F);
1891 printFunctionHead(F);
1892 printFunctionBody(F);
1893 Out << "return " << getCppName(F) << ";\n";
1894 Out << "}\n";
1895}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001896
Chris Lattner7e6d7452010-06-21 23:12:56 +00001897void CppWriter::printFunctions() {
1898 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1899 Module::const_iterator I = funcs.begin();
1900 Module::const_iterator IE = funcs.end();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001901
Chris Lattner7e6d7452010-06-21 23:12:56 +00001902 for (; I != IE; ++I) {
1903 const Function &func = *I;
1904 if (!func.isDeclaration()) {
1905 std::string name("define_");
1906 name += func.getName();
1907 printFunction(name, func.getName());
Anton Korobeynikov50276522008-04-23 22:29:24 +00001908 }
1909 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001910}
Anton Korobeynikov50276522008-04-23 22:29:24 +00001911
Chris Lattner7e6d7452010-06-21 23:12:56 +00001912void CppWriter::printVariable(const std::string& fname,
1913 const std::string& varName) {
1914 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001915
Chris Lattner7e6d7452010-06-21 23:12:56 +00001916 if (!GV) {
1917 error(std::string("Variable '") + varName + "' not found in input module");
1918 return;
1919 }
1920 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1921 printVariableUses(GV);
1922 printVariableHead(GV);
1923 printVariableBody(GV);
1924 Out << "return " << getCppName(GV) << ";\n";
1925 Out << "}\n";
1926}
1927
1928void CppWriter::printType(const std::string& fname,
1929 const std::string& typeName) {
1930 const Type* Ty = TheModule->getTypeByName(typeName);
1931 if (!Ty) {
1932 error(std::string("Type '") + typeName + "' not found in input module");
1933 return;
1934 }
1935 Out << "\nType* " << fname << "(Module *mod) {\n";
1936 printType(Ty);
1937 Out << "return " << getCppName(Ty) << ";\n";
1938 Out << "}\n";
1939}
1940
1941bool CppWriter::runOnModule(Module &M) {
1942 TheModule = &M;
1943
1944 // Emit a header
1945 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1946
1947 // Get the name of the function we're supposed to generate
1948 std::string fname = FuncName.getValue();
1949
1950 // Get the name of the thing we are to generate
1951 std::string tgtname = NameToGenerate.getValue();
1952 if (GenerationType == GenModule ||
1953 GenerationType == GenContents ||
1954 GenerationType == GenProgram ||
1955 GenerationType == GenFunctions) {
1956 if (tgtname == "!bad!") {
1957 if (M.getModuleIdentifier() == "-")
1958 tgtname = "<stdin>";
1959 else
1960 tgtname = M.getModuleIdentifier();
Anton Korobeynikov50276522008-04-23 22:29:24 +00001961 }
Chris Lattner7e6d7452010-06-21 23:12:56 +00001962 } else if (tgtname == "!bad!")
1963 error("You must use the -for option with -gen-{function,variable,type}");
1964
1965 switch (WhatToGenerate(GenerationType)) {
1966 case GenProgram:
1967 if (fname.empty())
1968 fname = "makeLLVMModule";
1969 printProgram(fname,tgtname);
1970 break;
1971 case GenModule:
1972 if (fname.empty())
1973 fname = "makeLLVMModule";
1974 printModule(fname,tgtname);
1975 break;
1976 case GenContents:
1977 if (fname.empty())
1978 fname = "makeLLVMModuleContents";
1979 printContents(fname,tgtname);
1980 break;
1981 case GenFunction:
1982 if (fname.empty())
1983 fname = "makeLLVMFunction";
1984 printFunction(fname,tgtname);
1985 break;
1986 case GenFunctions:
1987 printFunctions();
1988 break;
1989 case GenInline:
1990 if (fname.empty())
1991 fname = "makeLLVMInline";
1992 printInline(fname,tgtname);
1993 break;
1994 case GenVariable:
1995 if (fname.empty())
1996 fname = "makeLLVMVariable";
1997 printVariable(fname,tgtname);
1998 break;
1999 case GenType:
2000 if (fname.empty())
2001 fname = "makeLLVMType";
2002 printType(fname,tgtname);
2003 break;
2004 default:
2005 error("Invalid generation option");
Anton Korobeynikov50276522008-04-23 22:29:24 +00002006 }
2007
Chris Lattner7e6d7452010-06-21 23:12:56 +00002008 return false;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002009}
2010
2011char CppWriter::ID = 0;
2012
2013//===----------------------------------------------------------------------===//
2014// External Interface declaration
2015//===----------------------------------------------------------------------===//
2016
Dan Gohman99dca4f2010-05-11 19:57:55 +00002017bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2018 formatted_raw_ostream &o,
2019 CodeGenFileType FileType,
2020 CodeGenOpt::Level OptLevel,
2021 bool DisableVerify) {
Chris Lattner211edae2010-02-02 21:06:45 +00002022 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
Anton Korobeynikov50276522008-04-23 22:29:24 +00002023 PM.add(new CppWriter(o));
2024 return false;
2025}