blob: 1f08775894941906efda561e5be86d51edf3dd5d [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;
102
103 public:
104 static char ID;
David Greene71847812009-07-14 20:18:05 +0000105 explicit CppWriter(formatted_raw_ostream &o) :
Dan Gohmanae73dc12008-09-04 17:05:41 +0000106 ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
Anton Korobeynikov50276522008-04-23 22:29:24 +0000107
108 virtual const char *getPassName() const { return "C++ backend"; }
109
110 bool runOnModule(Module &M);
111
Anton Korobeynikov50276522008-04-23 22:29:24 +0000112 void printProgram(const std::string& fname, const std::string& modName );
113 void printModule(const std::string& fname, const std::string& modName );
114 void printContents(const std::string& fname, const std::string& modName );
115 void printFunction(const std::string& fname, const std::string& funcName );
116 void printFunctions();
117 void printInline(const std::string& fname, const std::string& funcName );
118 void printVariable(const std::string& fname, const std::string& varName );
119 void printType(const std::string& fname, const std::string& typeName );
120
121 void error(const std::string& msg);
122
123 private:
124 void printLinkageType(GlobalValue::LinkageTypes LT);
125 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000126 void printCallingConv(CallingConv::ID cc);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000127 void printEscapedString(const std::string& str);
128 void printCFP(const ConstantFP* CFP);
129
130 std::string getCppName(const Type* val);
131 inline void printCppName(const Type* val);
132
133 std::string getCppName(const Value* val);
134 inline void printCppName(const Value* val);
135
Devang Patel05988662008-09-25 21:00:45 +0000136 void printAttributes(const AttrListPtr &PAL, const std::string &name);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000137 bool printTypeInternal(const Type* Ty);
138 inline void printType(const Type* Ty);
139 void printTypes(const Module* M);
140
141 void printConstant(const Constant *CPV);
142 void printConstants(const Module* M);
143
144 void printVariableUses(const GlobalVariable *GV);
145 void printVariableHead(const GlobalVariable *GV);
146 void printVariableBody(const GlobalVariable *GV);
147
148 void printFunctionUses(const Function *F);
149 void printFunctionHead(const Function *F);
150 void printFunctionBody(const Function *F);
151 void printInstruction(const Instruction *I, const std::string& bbname);
152 std::string getOpName(Value*);
153
154 void printModuleBody();
155 };
156
157 static unsigned indent_level = 0;
David Greene71847812009-07-14 20:18:05 +0000158 inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000159 Out << "\n";
160 if (delta >= 0 || indent_level >= unsigned(-delta))
161 indent_level += delta;
162 for (unsigned i = 0; i < indent_level; ++i)
163 Out << " ";
164 return Out;
165 }
166
167 inline void in() { indent_level++; }
168 inline void out() { if (indent_level >0) indent_level--; }
169
170 inline void
171 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
177 inline std::string
178 getTypePrefix(const Type* Ty ) {
179 switch (Ty->getTypeID()) {
180 case Type::VoidTyID: return "void_";
181 case Type::IntegerTyID:
182 return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
183 "_";
184 case Type::FloatTyID: return "float_";
185 case Type::DoubleTyID: return "double_";
186 case Type::LabelTyID: return "label_";
187 case Type::FunctionTyID: return "func_";
188 case Type::StructTyID: return "struct_";
189 case Type::ArrayTyID: return "array_";
190 case Type::PointerTyID: return "ptr_";
191 case Type::VectorTyID: return "packed_";
192 case Type::OpaqueTyID: return "opaque_";
193 default: return "other_";
194 }
195 return "unknown_";
196 }
197
198 // Looks up the type in the symbol table and returns a pointer to its name or
199 // a null pointer if it wasn't found. Note that this isn't the same as the
200 // Mode::getTypeName function which will return an empty string, not a null
201 // pointer if the name is not found.
202 inline const std::string*
203 findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
204 TypeSymbolTable::const_iterator TI = ST.begin();
205 TypeSymbolTable::const_iterator TE = ST.end();
206 for (;TI != TE; ++TI)
207 if (TI->second == Ty)
208 return &(TI->first);
209 return 0;
210 }
211
212 void CppWriter::error(const std::string& msg) {
Torok Edwin30464702009-07-08 20:55:50 +0000213 llvm_report_error(msg);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000214 }
215
216 // printCFP - Print a floating point constant .. very carefully :)
217 // This makes sure that conversion to/from floating yields the same binary
218 // result so that we don't lose precision.
219 void CppWriter::printCFP(const ConstantFP *CFP) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000220 bool ignored;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000221 APFloat APF = APFloat(CFP->getValueAPF()); // copy
Owen Anderson1d0be152009-08-13 21:58:54 +0000222 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
Dale Johannesen23a98552008-10-09 23:00:39 +0000223 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Anton Korobeynikovd083dfb2009-08-21 12:50:54 +0000224 Out << "ConstantFP::get(getGlobalContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000225 Out << "APFloat(";
226#if HAVE_PRINTF_A
227 char Buffer[100];
228 sprintf(Buffer, "%A", APF.convertToDouble());
229 if ((!strncmp(Buffer, "0x", 2) ||
230 !strncmp(Buffer, "-0x", 3) ||
231 !strncmp(Buffer, "+0x", 3)) &&
232 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000233 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
Anton Korobeynikov50276522008-04-23 22:29:24 +0000234 Out << "BitsToDouble(" << Buffer << ")";
235 else
236 Out << "BitsToFloat((float)" << Buffer << ")";
237 Out << ")";
238 } else {
239#endif
240 std::string StrVal = ftostr(CFP->getValueAPF());
241
242 while (StrVal[0] == ' ')
243 StrVal.erase(StrVal.begin());
244
245 // Check to make sure that the stringized number is not some string like
246 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
247 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
248 ((StrVal[0] == '-' || StrVal[0] == '+') &&
249 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
250 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000251 if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
Anton Korobeynikov50276522008-04-23 22:29:24 +0000252 Out << StrVal;
253 else
254 Out << StrVal << "f";
Owen Anderson1d0be152009-08-13 21:58:54 +0000255 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
Owen Andersoncb371882008-08-21 00:14:44 +0000256 Out << "BitsToDouble(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000257 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000258 << "ULL) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000259 else
Owen Andersoncb371882008-08-21 00:14:44 +0000260 Out << "BitsToFloat(0x"
Dale Johannesen7111b022008-10-09 18:53:47 +0000261 << utohexstr((uint32_t)CFP->getValueAPF().
262 bitcastToAPInt().getZExtValue())
Owen Andersoncb371882008-08-21 00:14:44 +0000263 << "U) /* " << StrVal << " */";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000264 Out << ")";
265#if HAVE_PRINTF_A
266 }
267#endif
268 Out << ")";
269 }
270
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000271 void CppWriter::printCallingConv(CallingConv::ID cc){
Anton Korobeynikov50276522008-04-23 22:29:24 +0000272 // Print the calling convention.
273 switch (cc) {
274 case CallingConv::C: Out << "CallingConv::C"; break;
275 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
276 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
277 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
278 default: Out << cc; break;
279 }
280 }
281
282 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
283 switch (LT) {
284 case GlobalValue::InternalLinkage:
285 Out << "GlobalValue::InternalLinkage"; break;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000286 case GlobalValue::PrivateLinkage:
287 Out << "GlobalValue::PrivateLinkage"; break;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000288 case GlobalValue::LinkerPrivateLinkage:
289 Out << "GlobalValue::LinkerPrivateLinkage"; break;
Chris Lattner266c7bb2009-04-13 05:44:34 +0000290 case GlobalValue::AvailableExternallyLinkage:
291 Out << "GlobalValue::AvailableExternallyLinkage "; break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000292 case GlobalValue::LinkOnceAnyLinkage:
293 Out << "GlobalValue::LinkOnceAnyLinkage "; break;
294 case GlobalValue::LinkOnceODRLinkage:
295 Out << "GlobalValue::LinkOnceODRLinkage "; break;
296 case GlobalValue::WeakAnyLinkage:
297 Out << "GlobalValue::WeakAnyLinkage"; break;
298 case GlobalValue::WeakODRLinkage:
299 Out << "GlobalValue::WeakODRLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000300 case GlobalValue::AppendingLinkage:
301 Out << "GlobalValue::AppendingLinkage"; break;
302 case GlobalValue::ExternalLinkage:
303 Out << "GlobalValue::ExternalLinkage"; break;
304 case GlobalValue::DLLImportLinkage:
305 Out << "GlobalValue::DLLImportLinkage"; break;
306 case GlobalValue::DLLExportLinkage:
307 Out << "GlobalValue::DLLExportLinkage"; break;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +0000308 case GlobalValue::ExternalWeakLinkage:
309 Out << "GlobalValue::ExternalWeakLinkage"; break;
Duncan Sands4dc2b392009-03-11 20:14:15 +0000310 case GlobalValue::CommonLinkage:
311 Out << "GlobalValue::CommonLinkage"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000312 }
313 }
314
315 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
316 switch (VisType) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000317 default: llvm_unreachable("Unknown GVar visibility");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000318 case GlobalValue::DefaultVisibility:
319 Out << "GlobalValue::DefaultVisibility";
320 break;
321 case GlobalValue::HiddenVisibility:
322 Out << "GlobalValue::HiddenVisibility";
323 break;
324 case GlobalValue::ProtectedVisibility:
325 Out << "GlobalValue::ProtectedVisibility";
326 break;
327 }
328 }
329
330 // printEscapedString - Print each character of the specified string, escaping
331 // it if it is not printable or if it is an escape char.
332 void CppWriter::printEscapedString(const std::string &Str) {
333 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
334 unsigned char C = Str[i];
335 if (isprint(C) && C != '"' && C != '\\') {
336 Out << C;
337 } else {
338 Out << "\\x"
339 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
340 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
341 }
342 }
343 }
344
345 std::string CppWriter::getCppName(const Type* Ty) {
346 // First, handle the primitive types .. easy
347 if (Ty->isPrimitiveType() || Ty->isInteger()) {
348 switch (Ty->getTypeID()) {
Nicolas Geoffrayab2a6632009-08-15 14:47:42 +0000349 case Type::VoidTyID: return "Type::getVoidTy(getGlobalContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000350 case Type::IntegerTyID: {
351 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
Owen Anderson267a0ff2009-08-14 17:41:33 +0000352 return "IntegerType::get(getGlobalContext(), " + utostr(BitWidth) + ")";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000353 }
Nicolas Geoffrayab2a6632009-08-15 14:47:42 +0000354 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(getGlobalContext())";
355 case Type::FloatTyID: return "Type::getFloatTy(getGlobalContext())";
356 case Type::DoubleTyID: return "Type::getDoubleTy(getGlobalContext())";
357 case Type::LabelTyID: return "Type::getLabelTy(getGlobalContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000358 default:
359 error("Invalid primitive type");
360 break;
361 }
Nicolas Geoffrayab2a6632009-08-15 14:47:42 +0000362 // shouldn't be returned, but make it sensible
363 return "Type::getVoidTy(getGlobalContext())";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000364 }
365
366 // Now, see if we've seen the type before and return that
367 TypeMap::iterator I = TypeNames.find(Ty);
368 if (I != TypeNames.end())
369 return I->second;
370
371 // Okay, let's build a new name for this type. Start with a prefix
372 const char* prefix = 0;
373 switch (Ty->getTypeID()) {
374 case Type::FunctionTyID: prefix = "FuncTy_"; break;
375 case Type::StructTyID: prefix = "StructTy_"; break;
376 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
377 case Type::PointerTyID: prefix = "PointerTy_"; break;
378 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
379 case Type::VectorTyID: prefix = "VectorTy_"; break;
380 default: prefix = "OtherTy_"; break; // prevent breakage
381 }
382
383 // See if the type has a name in the symboltable and build accordingly
384 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
385 std::string name;
386 if (tName)
387 name = std::string(prefix) + *tName;
388 else
389 name = std::string(prefix) + utostr(uniqueNum++);
390 sanitize(name);
391
392 // Save the name
393 return TypeNames[Ty] = name;
394 }
395
396 void CppWriter::printCppName(const Type* Ty) {
397 printEscapedString(getCppName(Ty));
398 }
399
400 std::string CppWriter::getCppName(const Value* val) {
401 std::string name;
402 ValueMap::iterator I = ValueNames.find(val);
403 if (I != ValueNames.end() && I->first == val)
404 return I->second;
405
406 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
407 name = std::string("gvar_") +
408 getTypePrefix(GV->getType()->getElementType());
409 } else if (isa<Function>(val)) {
410 name = std::string("func_");
411 } else if (const Constant* C = dyn_cast<Constant>(val)) {
412 name = std::string("const_") + getTypePrefix(C->getType());
413 } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
414 if (is_inline) {
415 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
416 Function::const_arg_iterator(Arg)) + 1;
417 name = std::string("arg_") + utostr(argNum);
418 NameSet::iterator NI = UsedNames.find(name);
419 if (NI != UsedNames.end())
420 name += std::string("_") + utostr(uniqueNum++);
421 UsedNames.insert(name);
422 return ValueNames[val] = name;
423 } else {
424 name = getTypePrefix(val->getType());
425 }
426 } else {
427 name = getTypePrefix(val->getType());
428 }
Daniel Dunbar8f603022009-07-22 21:10:12 +0000429 if (val->hasName())
430 name += val->getName();
431 else
432 name += utostr(uniqueNum++);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000433 sanitize(name);
434 NameSet::iterator NI = UsedNames.find(name);
435 if (NI != UsedNames.end())
436 name += std::string("_") + utostr(uniqueNum++);
437 UsedNames.insert(name);
438 return ValueNames[val] = name;
439 }
440
441 void CppWriter::printCppName(const Value* val) {
442 printEscapedString(getCppName(val));
443 }
444
Devang Patel05988662008-09-25 21:00:45 +0000445 void CppWriter::printAttributes(const AttrListPtr &PAL,
Anton Korobeynikov50276522008-04-23 22:29:24 +0000446 const std::string &name) {
Devang Patel05988662008-09-25 21:00:45 +0000447 Out << "AttrListPtr " << name << "_PAL;";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000448 nl(Out);
449 if (!PAL.isEmpty()) {
450 Out << '{'; in(); nl(Out);
Devang Patel05988662008-09-25 21:00:45 +0000451 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
452 Out << "AttributeWithIndex PAWI;"; nl(Out);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000453 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000454 unsigned index = PAL.getSlot(i).Index;
Devang Pateleaf42ab2008-09-23 23:03:40 +0000455 Attributes attrs = PAL.getSlot(i).Attrs;
Nicolas Geoffrayd9afb4d2008-11-08 15:36:01 +0000456 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
Chris Lattneracca9552009-01-13 07:22:22 +0000457#define HANDLE_ATTR(X) \
458 if (attrs & Attribute::X) \
459 Out << " | Attribute::" #X; \
460 attrs &= ~Attribute::X;
461
462 HANDLE_ATTR(SExt);
463 HANDLE_ATTR(ZExt);
Chris Lattneracca9552009-01-13 07:22:22 +0000464 HANDLE_ATTR(NoReturn);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000465 HANDLE_ATTR(InReg);
466 HANDLE_ATTR(StructRet);
Chris Lattneracca9552009-01-13 07:22:22 +0000467 HANDLE_ATTR(NoUnwind);
Chris Lattneracca9552009-01-13 07:22:22 +0000468 HANDLE_ATTR(NoAlias);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000469 HANDLE_ATTR(ByVal);
Chris Lattneracca9552009-01-13 07:22:22 +0000470 HANDLE_ATTR(Nest);
471 HANDLE_ATTR(ReadNone);
472 HANDLE_ATTR(ReadOnly);
Jeffrey Yasskin2d92c712009-05-28 03:16:17 +0000473 HANDLE_ATTR(NoInline);
474 HANDLE_ATTR(AlwaysInline);
475 HANDLE_ATTR(OptimizeForSize);
476 HANDLE_ATTR(StackProtect);
477 HANDLE_ATTR(StackProtectReq);
Chris Lattneracca9552009-01-13 07:22:22 +0000478 HANDLE_ATTR(NoCapture);
479#undef HANDLE_ATTR
480 assert(attrs == 0 && "Unhandled attribute!");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000481 Out << ";";
482 nl(Out);
483 Out << "Attrs.push_back(PAWI);";
484 nl(Out);
485 }
Devang Patel05988662008-09-25 21:00:45 +0000486 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000487 nl(Out);
488 out(); nl(Out);
489 Out << '}'; nl(Out);
490 }
491 }
492
493 bool CppWriter::printTypeInternal(const Type* Ty) {
494 // We don't print definitions for primitive types
495 if (Ty->isPrimitiveType() || Ty->isInteger())
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()) {
Nicolas Geoffraybad9def2009-08-15 15:41:32 +0000515 Out << "PATypeHolder " << typeName;
516 Out << "_fwd = OpaqueType::get(getGlobalContext());";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000517 nl(Out);
518 UnresolvedTypes[Ty] = typeName;
519 }
520 return true;
521 }
522
523 // 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);
527
528 // 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;
541 if (isForward)
542 Out << "_fwd";
543 Out << ");";
544 nl(Out);
545 }
546 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();
556 nl(Out);
557 break;
558 }
559 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 << ");";
573 nl(Out);
574 }
575 Out << "StructType* " << typeName << " = StructType::get("
Nicolas Geoffray6f62cff2009-08-06 21:31:35 +0000576 << "mod->getContext(), "
Anton Korobeynikov50276522008-04-23 22:29:24 +0000577 << 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: {
Nicolas Geoffraybad9def2009-08-15 15:41:32 +0000616 Out << "OpaqueType* " << typeName;
617 Out << " = OpaqueType::get(getGlobalContext());";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000618 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.
673 void CppWriter::printType(const Type* Ty) {
674 assert(TypeStack.empty());
675 TypeStack.clear();
676 printTypeInternal(Ty);
677 assert(TypeStack.empty());
678 }
679
680 void 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->isInteger() || 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());
728 }
729 }
730 }
731 }
732
733
734 // printConstant - Print out a constant pool entry...
735 void 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()));
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000744
Anton Korobeynikov50276522008-04-23 22:29:24 +0000745 if (isa<GlobalValue>(CV)) {
746 // Skip variables and functions, we emit them elsewhere
747 return;
748 }
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000749
Anton Korobeynikov50276522008-04-23 22:29:24 +0000750 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Anton Korobeynikov70053c32008-08-18 20:03:45 +0000751 std::string constValue = CI->getValue().toString(10, true);
Owen Anderson267a0ff2009-08-14 17:41:33 +0000752 Out << "ConstantInt* " << constName
753 << " = ConstantInt::get(getGlobalContext(), APInt("
754 << cast<IntegerType>(CI->getType())->getBitWidth()
Benjamin Kramer6d5f0f02009-09-03 14:58:24 +0000755 << ", StringRef(\"" << constValue << "\"), 10));";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000756 } else if (isa<ConstantAggregateZero>(CV)) {
757 Out << "ConstantAggregateZero* " << constName
758 << " = ConstantAggregateZero::get(" << typeName << ");";
759 } else if (isa<ConstantPointerNull>(CV)) {
760 Out << "ConstantPointerNull* " << constName
Anton Korobeynikovff4ca2e2008-10-05 15:07:06 +0000761 << " = ConstantPointerNull::get(" << typeName << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000762 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
763 Out << "ConstantFP* " << constName << " = ";
764 printCFP(CFP);
765 Out << ";";
766 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000767 if (CA->isString() &&
768 CA->getType()->getElementType() ==
769 Type::getInt8Ty(CA->getContext())) {
Owen Anderson267a0ff2009-08-14 17:41:33 +0000770 Out << "Constant* " << constName <<
771 " = ConstantArray::get(getGlobalContext(), \"";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000772 std::string tmp = CA->getAsString();
773 bool nullTerminate = false;
774 if (tmp[tmp.length()-1] == 0) {
775 tmp.erase(tmp.length()-1);
776 nullTerminate = true;
777 }
778 printEscapedString(tmp);
779 // Determine if we want null termination or not.
780 if (nullTerminate)
781 Out << "\", true"; // Indicate that the null terminator should be
782 // added.
783 else
784 Out << "\", false";// No null terminator
785 Out << ");";
786 } else {
787 Out << "std::vector<Constant*> " << constName << "_elems;";
788 nl(Out);
789 unsigned N = CA->getNumOperands();
790 for (unsigned i = 0; i < N; ++i) {
791 printConstant(CA->getOperand(i)); // recurse to print operands
792 Out << constName << "_elems.push_back("
793 << getCppName(CA->getOperand(i)) << ");";
794 nl(Out);
795 }
796 Out << "Constant* " << constName << " = ConstantArray::get("
797 << typeName << ", " << constName << "_elems);";
798 }
799 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
800 Out << "std::vector<Constant*> " << constName << "_fields;";
801 nl(Out);
802 unsigned N = CS->getNumOperands();
803 for (unsigned i = 0; i < N; i++) {
804 printConstant(CS->getOperand(i));
805 Out << constName << "_fields.push_back("
806 << getCppName(CS->getOperand(i)) << ");";
807 nl(Out);
808 }
809 Out << "Constant* " << constName << " = ConstantStruct::get("
810 << typeName << ", " << constName << "_fields);";
811 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
812 Out << "std::vector<Constant*> " << constName << "_elems;";
813 nl(Out);
814 unsigned N = CP->getNumOperands();
815 for (unsigned i = 0; i < N; ++i) {
816 printConstant(CP->getOperand(i));
817 Out << constName << "_elems.push_back("
818 << getCppName(CP->getOperand(i)) << ");";
819 nl(Out);
820 }
821 Out << "Constant* " << constName << " = ConstantVector::get("
822 << typeName << ", " << constName << "_elems);";
823 } else if (isa<UndefValue>(CV)) {
824 Out << "UndefValue* " << constName << " = UndefValue::get("
825 << typeName << ");";
826 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
827 if (CE->getOpcode() == Instruction::GetElementPtr) {
828 Out << "std::vector<Constant*> " << constName << "_indices;";
829 nl(Out);
830 printConstant(CE->getOperand(0));
831 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
832 printConstant(CE->getOperand(i));
833 Out << constName << "_indices.push_back("
834 << getCppName(CE->getOperand(i)) << ");";
835 nl(Out);
836 }
837 Out << "Constant* " << constName
838 << " = ConstantExpr::getGetElementPtr("
839 << getCppName(CE->getOperand(0)) << ", "
840 << "&" << constName << "_indices[0], "
841 << constName << "_indices.size()"
Benjamin Kramer6d5f0f02009-09-03 14:58:24 +0000842 << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000843 } else if (CE->isCast()) {
844 printConstant(CE->getOperand(0));
845 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
846 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000847 default: llvm_unreachable("Invalid cast opcode");
Anton Korobeynikov50276522008-04-23 22:29:24 +0000848 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
849 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
850 case Instruction::SExt: Out << "Instruction::SExt"; break;
851 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
852 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
853 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
854 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
855 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
856 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
857 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
858 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
859 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
860 }
861 Out << ", " << getCppName(CE->getOperand(0)) << ", "
862 << getCppName(CE->getType()) << ");";
863 } else {
864 unsigned N = CE->getNumOperands();
865 for (unsigned i = 0; i < N; ++i ) {
866 printConstant(CE->getOperand(i));
867 }
868 Out << "Constant* " << constName << " = ConstantExpr::";
869 switch (CE->getOpcode()) {
870 case Instruction::Add: Out << "getAdd("; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000871 case Instruction::FAdd: Out << "getFAdd("; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000872 case Instruction::Sub: Out << "getSub("; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000873 case Instruction::FSub: Out << "getFSub("; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000874 case Instruction::Mul: Out << "getMul("; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000875 case Instruction::FMul: Out << "getFMul("; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +0000876 case Instruction::UDiv: Out << "getUDiv("; break;
877 case Instruction::SDiv: Out << "getSDiv("; break;
878 case Instruction::FDiv: Out << "getFDiv("; break;
879 case Instruction::URem: Out << "getURem("; break;
880 case Instruction::SRem: Out << "getSRem("; break;
881 case Instruction::FRem: Out << "getFRem("; break;
882 case Instruction::And: Out << "getAnd("; break;
883 case Instruction::Or: Out << "getOr("; break;
884 case Instruction::Xor: Out << "getXor("; break;
885 case Instruction::ICmp:
886 Out << "getICmp(ICmpInst::ICMP_";
887 switch (CE->getPredicate()) {
888 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
889 case ICmpInst::ICMP_NE: Out << "NE"; break;
890 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
891 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
892 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
893 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
894 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
895 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
896 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
897 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
898 default: error("Invalid ICmp Predicate");
899 }
900 break;
901 case Instruction::FCmp:
902 Out << "getFCmp(FCmpInst::FCMP_";
903 switch (CE->getPredicate()) {
904 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
905 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
906 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
907 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
908 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
909 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
910 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
911 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
912 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
913 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
914 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
915 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
916 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
917 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
918 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
919 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
920 default: error("Invalid FCmp Predicate");
921 }
922 break;
923 case Instruction::Shl: Out << "getShl("; break;
924 case Instruction::LShr: Out << "getLShr("; break;
925 case Instruction::AShr: Out << "getAShr("; break;
926 case Instruction::Select: Out << "getSelect("; break;
927 case Instruction::ExtractElement: Out << "getExtractElement("; break;
928 case Instruction::InsertElement: Out << "getInsertElement("; break;
929 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
930 default:
931 error("Invalid constant expression");
932 break;
933 }
934 Out << getCppName(CE->getOperand(0));
935 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
936 Out << ", " << getCppName(CE->getOperand(i));
937 Out << ");";
938 }
939 } else {
940 error("Bad Constant");
941 Out << "Constant* " << constName << " = 0; ";
942 }
943 nl(Out);
944 }
945
946 void CppWriter::printConstants(const Module* M) {
947 // Traverse all the global variables looking for constant initializers
948 for (Module::const_global_iterator I = TheModule->global_begin(),
949 E = TheModule->global_end(); I != E; ++I)
950 if (I->hasInitializer())
951 printConstant(I->getInitializer());
952
953 // Traverse the LLVM functions looking for constants
954 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
955 FI != FE; ++FI) {
956 // Add all of the basic blocks and instructions
957 for (Function::const_iterator BB = FI->begin(),
958 E = FI->end(); BB != E; ++BB) {
959 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
960 ++I) {
961 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
962 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
963 printConstant(C);
964 }
965 }
966 }
967 }
968 }
969 }
970
971 void CppWriter::printVariableUses(const GlobalVariable *GV) {
972 nl(Out) << "// Type Definitions";
973 nl(Out);
974 printType(GV->getType());
975 if (GV->hasInitializer()) {
Chris Lattnercdfb3022009-12-14 19:34:32 +0000976 Constant *Init = GV->getInitializer();
Anton Korobeynikov50276522008-04-23 22:29:24 +0000977 printType(Init->getType());
Chris Lattnercdfb3022009-12-14 19:34:32 +0000978 if (Function *F = dyn_cast<Function>(Init)) {
Anton Korobeynikov50276522008-04-23 22:29:24 +0000979 nl(Out)<< "/ Function Declarations"; nl(Out);
980 printFunctionHead(F);
981 } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
982 nl(Out) << "// Global Variable Declarations"; nl(Out);
983 printVariableHead(gv);
Chris Lattnercdfb3022009-12-14 19:34:32 +0000984
Anton Korobeynikov50276522008-04-23 22:29:24 +0000985 nl(Out) << "// Global Variable Definitions"; nl(Out);
986 printVariableBody(gv);
Chris Lattnercdfb3022009-12-14 19:34:32 +0000987 } else {
988 nl(Out) << "// Constant Definitions"; nl(Out);
989 printConstant(Init);
Anton Korobeynikov50276522008-04-23 22:29:24 +0000990 }
991 }
992 }
993
994 void CppWriter::printVariableHead(const GlobalVariable *GV) {
995 nl(Out) << "GlobalVariable* " << getCppName(GV);
996 if (is_inline) {
Owen Anderson267a0ff2009-08-14 17:41:33 +0000997 Out << " = mod->getGlobalVariable(getGlobalContext(), ";
Anton Korobeynikov50276522008-04-23 22:29:24 +0000998 printEscapedString(GV->getName());
999 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
1000 nl(Out) << "if (!" << getCppName(GV) << ") {";
1001 in(); nl(Out) << getCppName(GV);
1002 }
Owen Anderson267a0ff2009-08-14 17:41:33 +00001003 Out << " = new GlobalVariable(/*Module=*/*mod, ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001004 nl(Out) << "/*Type=*/";
1005 printCppName(GV->getType()->getElementType());
1006 Out << ",";
1007 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1008 Out << ",";
1009 nl(Out) << "/*Linkage=*/";
1010 printLinkageType(GV->getLinkage());
1011 Out << ",";
1012 nl(Out) << "/*Initializer=*/0, ";
1013 if (GV->hasInitializer()) {
1014 Out << "// has initializer, specified below";
1015 }
1016 nl(Out) << "/*Name=*/\"";
1017 printEscapedString(GV->getName());
Owen Anderson16a412e2009-07-10 16:42:19 +00001018 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001019 nl(Out);
1020
1021 if (GV->hasSection()) {
1022 printCppName(GV);
1023 Out << "->setSection(\"";
1024 printEscapedString(GV->getSection());
1025 Out << "\");";
1026 nl(Out);
1027 }
1028 if (GV->getAlignment()) {
1029 printCppName(GV);
1030 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1031 nl(Out);
1032 }
1033 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1034 printCppName(GV);
1035 Out << "->setVisibility(";
1036 printVisibilityType(GV->getVisibility());
1037 Out << ");";
1038 nl(Out);
1039 }
1040 if (is_inline) {
1041 out(); Out << "}"; nl(Out);
1042 }
1043 }
1044
1045 void CppWriter::printVariableBody(const GlobalVariable *GV) {
1046 if (GV->hasInitializer()) {
1047 printCppName(GV);
1048 Out << "->setInitializer(";
1049 Out << getCppName(GV->getInitializer()) << ");";
1050 nl(Out);
1051 }
1052 }
1053
1054 std::string CppWriter::getOpName(Value* V) {
1055 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1056 return getCppName(V);
1057
1058 // See if its alread in the map of forward references, if so just return the
1059 // name we already set up for it
1060 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1061 if (I != ForwardRefs.end())
1062 return I->second;
1063
1064 // This is a new forward reference. Generate a unique name for it
1065 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1066
1067 // Yes, this is a hack. An Argument is the smallest instantiable value that
1068 // we can make as a placeholder for the real value. We'll replace these
1069 // Argument instances later.
1070 Out << "Argument* " << result << " = new Argument("
1071 << getCppName(V->getType()) << ");";
1072 nl(Out);
1073 ForwardRefs[V] = result;
1074 return result;
1075 }
1076
1077 // printInstruction - This member is called for each Instruction in a function.
1078 void CppWriter::printInstruction(const Instruction *I,
1079 const std::string& bbname) {
1080 std::string iName(getCppName(I));
1081
1082 // Before we emit this instruction, we need to take care of generating any
1083 // forward references. So, we get the names of all the operands in advance
1084 std::string* opNames = new std::string[I->getNumOperands()];
1085 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1086 opNames[i] = getOpName(I->getOperand(i));
1087 }
1088
1089 switch (I->getOpcode()) {
Dan Gohman26825a82008-06-09 14:09:13 +00001090 default:
1091 error("Invalid instruction");
1092 break;
1093
Anton Korobeynikov50276522008-04-23 22:29:24 +00001094 case Instruction::Ret: {
1095 const ReturnInst* ret = cast<ReturnInst>(I);
Owen Anderson267a0ff2009-08-14 17:41:33 +00001096 Out << "ReturnInst::Create(getGlobalContext(), "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001097 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1098 break;
1099 }
1100 case Instruction::Br: {
1101 const BranchInst* br = cast<BranchInst>(I);
1102 Out << "BranchInst::Create(" ;
1103 if (br->getNumOperands() == 3 ) {
Anton Korobeynikovcffb5282009-05-04 19:10:38 +00001104 Out << opNames[2] << ", "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001105 << opNames[1] << ", "
Anton Korobeynikovcffb5282009-05-04 19:10:38 +00001106 << opNames[0] << ", ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001107
1108 } else if (br->getNumOperands() == 1) {
1109 Out << opNames[0] << ", ";
1110 } else {
1111 error("Branch with 2 operands?");
1112 }
1113 Out << bbname << ");";
1114 break;
1115 }
1116 case Instruction::Switch: {
Chris Lattner627b4702009-10-27 21:24:48 +00001117 const SwitchInst *SI = cast<SwitchInst>(I);
Anton Korobeynikov50276522008-04-23 22:29:24 +00001118 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1119 << opNames[0] << ", "
1120 << opNames[1] << ", "
Chris Lattner627b4702009-10-27 21:24:48 +00001121 << SI->getNumCases() << ", " << bbname << ");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001122 nl(Out);
Chris Lattner627b4702009-10-27 21:24:48 +00001123 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001124 Out << iName << "->addCase("
1125 << opNames[i] << ", "
1126 << opNames[i+1] << ");";
1127 nl(Out);
1128 }
1129 break;
1130 }
Chris Lattnerab21db72009-10-28 00:19:10 +00001131 case Instruction::IndirectBr: {
1132 const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
1133 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
Chris Lattner627b4702009-10-27 21:24:48 +00001134 << opNames[0] << ", " << IBI->getNumDestinations() << ");";
1135 nl(Out);
1136 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
1137 Out << iName << "->addDestination(" << opNames[i] << ");";
1138 nl(Out);
1139 }
1140 break;
1141 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001142 case Instruction::Invoke: {
1143 const InvokeInst* inv = cast<InvokeInst>(I);
1144 Out << "std::vector<Value*> " << iName << "_params;";
1145 nl(Out);
1146 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1147 Out << iName << "_params.push_back("
1148 << opNames[i] << ");";
1149 nl(Out);
1150 }
1151 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1152 << opNames[0] << ", "
1153 << opNames[1] << ", "
1154 << opNames[2] << ", "
1155 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1156 printEscapedString(inv->getName());
1157 Out << "\", " << bbname << ");";
1158 nl(Out) << iName << "->setCallingConv(";
1159 printCallingConv(inv->getCallingConv());
1160 Out << ");";
Devang Patel05988662008-09-25 21:00:45 +00001161 printAttributes(inv->getAttributes(), iName);
1162 Out << iName << "->setAttributes(" << iName << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001163 nl(Out);
1164 break;
1165 }
1166 case Instruction::Unwind: {
1167 Out << "new UnwindInst("
1168 << bbname << ");";
1169 break;
1170 }
Reid Kleckner781c2b82009-08-19 22:38:37 +00001171 case Instruction::Unreachable: {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001172 Out << "new UnreachableInst("
Reid Kleckner781c2b82009-08-19 22:38:37 +00001173 << "getGlobalContext(), "
Anton Korobeynikov50276522008-04-23 22:29:24 +00001174 << bbname << ");";
1175 break;
1176 }
1177 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001178 case Instruction::FAdd:
Anton Korobeynikov50276522008-04-23 22:29:24 +00001179 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001180 case Instruction::FSub:
Anton Korobeynikov50276522008-04-23 22:29:24 +00001181 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001182 case Instruction::FMul:
Anton Korobeynikov50276522008-04-23 22:29:24 +00001183 case Instruction::UDiv:
1184 case Instruction::SDiv:
1185 case Instruction::FDiv:
1186 case Instruction::URem:
1187 case Instruction::SRem:
1188 case Instruction::FRem:
1189 case Instruction::And:
1190 case Instruction::Or:
1191 case Instruction::Xor:
1192 case Instruction::Shl:
1193 case Instruction::LShr:
1194 case Instruction::AShr:{
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001195 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001196 switch (I->getOpcode()) {
1197 case Instruction::Add: Out << "Instruction::Add"; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001198 case Instruction::FAdd: Out << "Instruction::FAdd"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001199 case Instruction::Sub: Out << "Instruction::Sub"; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001200 case Instruction::FSub: Out << "Instruction::FSub"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001201 case Instruction::Mul: Out << "Instruction::Mul"; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001202 case Instruction::FMul: Out << "Instruction::FMul"; break;
Anton Korobeynikov50276522008-04-23 22:29:24 +00001203 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1204 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1205 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1206 case Instruction::URem:Out << "Instruction::URem"; break;
1207 case Instruction::SRem:Out << "Instruction::SRem"; break;
1208 case Instruction::FRem:Out << "Instruction::FRem"; break;
1209 case Instruction::And: Out << "Instruction::And"; break;
1210 case Instruction::Or: Out << "Instruction::Or"; break;
1211 case Instruction::Xor: Out << "Instruction::Xor"; break;
1212 case Instruction::Shl: Out << "Instruction::Shl"; break;
1213 case Instruction::LShr:Out << "Instruction::LShr"; break;
1214 case Instruction::AShr:Out << "Instruction::AShr"; break;
1215 default: Out << "Instruction::BadOpCode"; break;
1216 }
1217 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1218 printEscapedString(I->getName());
1219 Out << "\", " << bbname << ");";
1220 break;
1221 }
1222 case Instruction::FCmp: {
Anton Korobeynikovd083dfb2009-08-21 12:50:54 +00001223 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001224 switch (cast<FCmpInst>(I)->getPredicate()) {
1225 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1226 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1227 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1228 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1229 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1230 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1231 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1232 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1233 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1234 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1235 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1236 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1237 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1238 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1239 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1240 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1241 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1242 }
1243 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1244 printEscapedString(I->getName());
Anton Korobeynikovd083dfb2009-08-21 12:50:54 +00001245 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001246 break;
1247 }
1248 case Instruction::ICmp: {
Reid Kleckner781c2b82009-08-19 22:38:37 +00001249 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001250 switch (cast<ICmpInst>(I)->getPredicate()) {
1251 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1252 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1253 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1254 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1255 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1256 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1257 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1258 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1259 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1260 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1261 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1262 }
1263 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1264 printEscapedString(I->getName());
Reid Kleckner781c2b82009-08-19 22:38:37 +00001265 Out << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001266 break;
1267 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001268 case Instruction::Alloca: {
1269 const AllocaInst* allocaI = cast<AllocaInst>(I);
1270 Out << "AllocaInst* " << iName << " = new AllocaInst("
1271 << getCppName(allocaI->getAllocatedType()) << ", ";
1272 if (allocaI->isArrayAllocation())
1273 Out << opNames[0] << ", ";
1274 Out << "\"";
1275 printEscapedString(allocaI->getName());
1276 Out << "\", " << bbname << ");";
1277 if (allocaI->getAlignment())
1278 nl(Out) << iName << "->setAlignment("
1279 << allocaI->getAlignment() << ");";
1280 break;
1281 }
1282 case Instruction::Load:{
1283 const LoadInst* load = cast<LoadInst>(I);
1284 Out << "LoadInst* " << iName << " = new LoadInst("
1285 << opNames[0] << ", \"";
1286 printEscapedString(load->getName());
1287 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1288 << ", " << bbname << ");";
1289 break;
1290 }
1291 case Instruction::Store: {
1292 const StoreInst* store = cast<StoreInst>(I);
Anton Korobeynikovb0714db2008-11-09 02:54:13 +00001293 Out << " new StoreInst("
Anton Korobeynikov50276522008-04-23 22:29:24 +00001294 << opNames[0] << ", "
1295 << opNames[1] << ", "
1296 << (store->isVolatile() ? "true" : "false")
1297 << ", " << bbname << ");";
1298 break;
1299 }
1300 case Instruction::GetElementPtr: {
1301 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1302 if (gep->getNumOperands() <= 2) {
1303 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1304 << opNames[0];
1305 if (gep->getNumOperands() == 2)
1306 Out << ", " << opNames[1];
1307 } else {
1308 Out << "std::vector<Value*> " << iName << "_indices;";
1309 nl(Out);
1310 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1311 Out << iName << "_indices.push_back("
1312 << opNames[i] << ");";
1313 nl(Out);
1314 }
1315 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1316 << opNames[0] << ", " << iName << "_indices.begin(), "
1317 << iName << "_indices.end()";
1318 }
1319 Out << ", \"";
1320 printEscapedString(gep->getName());
1321 Out << "\", " << bbname << ");";
1322 break;
1323 }
1324 case Instruction::PHI: {
1325 const PHINode* phi = cast<PHINode>(I);
1326
1327 Out << "PHINode* " << iName << " = PHINode::Create("
1328 << getCppName(phi->getType()) << ", \"";
1329 printEscapedString(phi->getName());
1330 Out << "\", " << bbname << ");";
1331 nl(Out) << iName << "->reserveOperandSpace("
1332 << phi->getNumIncomingValues()
1333 << ");";
1334 nl(Out);
1335 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1336 Out << iName << "->addIncoming("
1337 << opNames[i] << ", " << opNames[i+1] << ");";
1338 nl(Out);
1339 }
1340 break;
1341 }
1342 case Instruction::Trunc:
1343 case Instruction::ZExt:
1344 case Instruction::SExt:
1345 case Instruction::FPTrunc:
1346 case Instruction::FPExt:
1347 case Instruction::FPToUI:
1348 case Instruction::FPToSI:
1349 case Instruction::UIToFP:
1350 case Instruction::SIToFP:
1351 case Instruction::PtrToInt:
1352 case Instruction::IntToPtr:
1353 case Instruction::BitCast: {
1354 const CastInst* cst = cast<CastInst>(I);
1355 Out << "CastInst* " << iName << " = new ";
1356 switch (I->getOpcode()) {
1357 case Instruction::Trunc: Out << "TruncInst"; break;
1358 case Instruction::ZExt: Out << "ZExtInst"; break;
1359 case Instruction::SExt: Out << "SExtInst"; break;
1360 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1361 case Instruction::FPExt: Out << "FPExtInst"; break;
1362 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1363 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1364 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1365 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1366 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1367 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1368 case Instruction::BitCast: Out << "BitCastInst"; break;
1369 default: assert(!"Unreachable"); break;
1370 }
1371 Out << "(" << opNames[0] << ", "
1372 << getCppName(cst->getType()) << ", \"";
1373 printEscapedString(cst->getName());
1374 Out << "\", " << bbname << ");";
1375 break;
1376 }
1377 case Instruction::Call:{
1378 const CallInst* call = cast<CallInst>(I);
Gabor Greif0c8f7dc2009-03-25 06:32:59 +00001379 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001380 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1381 << getCppName(ila->getFunctionType()) << ", \""
1382 << ila->getAsmString() << "\", \""
1383 << ila->getConstraintString() << "\","
1384 << (ila->hasSideEffects() ? "true" : "false") << ");";
1385 nl(Out);
1386 }
1387 if (call->getNumOperands() > 2) {
1388 Out << "std::vector<Value*> " << iName << "_params;";
1389 nl(Out);
1390 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1391 Out << iName << "_params.push_back(" << opNames[i] << ");";
1392 nl(Out);
1393 }
1394 Out << "CallInst* " << iName << " = CallInst::Create("
1395 << opNames[0] << ", " << iName << "_params.begin(), "
1396 << iName << "_params.end(), \"";
1397 } else if (call->getNumOperands() == 2) {
1398 Out << "CallInst* " << iName << " = CallInst::Create("
1399 << opNames[0] << ", " << opNames[1] << ", \"";
1400 } else {
1401 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1402 << ", \"";
1403 }
1404 printEscapedString(call->getName());
1405 Out << "\", " << bbname << ");";
1406 nl(Out) << iName << "->setCallingConv(";
1407 printCallingConv(call->getCallingConv());
1408 Out << ");";
1409 nl(Out) << iName << "->setTailCall("
1410 << (call->isTailCall() ? "true":"false");
1411 Out << ");";
Devang Patel05988662008-09-25 21:00:45 +00001412 printAttributes(call->getAttributes(), iName);
1413 Out << iName << "->setAttributes(" << iName << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001414 nl(Out);
1415 break;
1416 }
1417 case Instruction::Select: {
1418 const SelectInst* sel = cast<SelectInst>(I);
1419 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1420 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1421 printEscapedString(sel->getName());
1422 Out << "\", " << bbname << ");";
1423 break;
1424 }
1425 case Instruction::UserOp1:
1426 /// FALL THROUGH
1427 case Instruction::UserOp2: {
1428 /// FIXME: What should be done here?
1429 break;
1430 }
1431 case Instruction::VAArg: {
1432 const VAArgInst* va = cast<VAArgInst>(I);
1433 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1434 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1435 printEscapedString(va->getName());
1436 Out << "\", " << bbname << ");";
1437 break;
1438 }
1439 case Instruction::ExtractElement: {
1440 const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1441 Out << "ExtractElementInst* " << getCppName(eei)
1442 << " = new ExtractElementInst(" << opNames[0]
1443 << ", " << opNames[1] << ", \"";
1444 printEscapedString(eei->getName());
1445 Out << "\", " << bbname << ");";
1446 break;
1447 }
1448 case Instruction::InsertElement: {
1449 const InsertElementInst* iei = cast<InsertElementInst>(I);
1450 Out << "InsertElementInst* " << getCppName(iei)
1451 << " = InsertElementInst::Create(" << opNames[0]
1452 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1453 printEscapedString(iei->getName());
1454 Out << "\", " << bbname << ");";
1455 break;
1456 }
1457 case Instruction::ShuffleVector: {
1458 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1459 Out << "ShuffleVectorInst* " << getCppName(svi)
1460 << " = new ShuffleVectorInst(" << opNames[0]
1461 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1462 printEscapedString(svi->getName());
1463 Out << "\", " << bbname << ");";
1464 break;
1465 }
Dan Gohman75146a62008-06-09 14:12:10 +00001466 case Instruction::ExtractValue: {
1467 const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1468 Out << "std::vector<unsigned> " << iName << "_indices;";
1469 nl(Out);
1470 for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1471 Out << iName << "_indices.push_back("
1472 << evi->idx_begin()[i] << ");";
1473 nl(Out);
1474 }
1475 Out << "ExtractValueInst* " << getCppName(evi)
1476 << " = ExtractValueInst::Create(" << opNames[0]
1477 << ", "
1478 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1479 printEscapedString(evi->getName());
1480 Out << "\", " << bbname << ");";
1481 break;
1482 }
1483 case Instruction::InsertValue: {
1484 const InsertValueInst *ivi = cast<InsertValueInst>(I);
1485 Out << "std::vector<unsigned> " << iName << "_indices;";
1486 nl(Out);
1487 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1488 Out << iName << "_indices.push_back("
1489 << ivi->idx_begin()[i] << ");";
1490 nl(Out);
1491 }
1492 Out << "InsertValueInst* " << getCppName(ivi)
1493 << " = InsertValueInst::Create(" << opNames[0]
1494 << ", " << opNames[1] << ", "
1495 << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1496 printEscapedString(ivi->getName());
1497 Out << "\", " << bbname << ");";
1498 break;
1499 }
Anton Korobeynikov50276522008-04-23 22:29:24 +00001500 }
1501 DefinedValues.insert(I);
1502 nl(Out);
1503 delete [] opNames;
1504}
1505
1506 // Print out the types, constants and declarations needed by one function
1507 void CppWriter::printFunctionUses(const Function* F) {
1508 nl(Out) << "// Type Definitions"; nl(Out);
1509 if (!is_inline) {
1510 // Print the function's return type
1511 printType(F->getReturnType());
1512
1513 // Print the function's function type
1514 printType(F->getFunctionType());
1515
1516 // Print the types of each of the function's arguments
1517 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1518 AI != AE; ++AI) {
1519 printType(AI->getType());
1520 }
1521 }
1522
1523 // Print type definitions for every type referenced by an instruction and
1524 // make a note of any global values or constants that are referenced
1525 SmallPtrSet<GlobalValue*,64> gvs;
1526 SmallPtrSet<Constant*,64> consts;
1527 for (Function::const_iterator BB = F->begin(), BE = F->end();
1528 BB != BE; ++BB){
1529 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1530 I != E; ++I) {
1531 // Print the type of the instruction itself
1532 printType(I->getType());
1533
1534 // Print the type of each of the instruction's operands
1535 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1536 Value* operand = I->getOperand(i);
1537 printType(operand->getType());
1538
1539 // If the operand references a GVal or Constant, make a note of it
1540 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1541 gvs.insert(GV);
1542 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1543 if (GVar->hasInitializer())
1544 consts.insert(GVar->getInitializer());
1545 } else if (Constant* C = dyn_cast<Constant>(operand))
1546 consts.insert(C);
1547 }
1548 }
1549 }
1550
1551 // Print the function declarations for any functions encountered
1552 nl(Out) << "// Function Declarations"; nl(Out);
1553 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1554 I != E; ++I) {
1555 if (Function* Fun = dyn_cast<Function>(*I)) {
1556 if (!is_inline || Fun != F)
1557 printFunctionHead(Fun);
1558 }
1559 }
1560
1561 // Print the global variable declarations for any variables encountered
1562 nl(Out) << "// Global Variable Declarations"; nl(Out);
1563 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1564 I != E; ++I) {
1565 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1566 printVariableHead(F);
1567 }
1568
1569 // Print the constants found
1570 nl(Out) << "// Constant Definitions"; nl(Out);
1571 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1572 E = consts.end(); I != E; ++I) {
1573 printConstant(*I);
1574 }
1575
1576 // Process the global variables definitions now that all the constants have
1577 // been emitted. These definitions just couple the gvars with their constant
1578 // initializers.
1579 nl(Out) << "// Global Variable Definitions"; nl(Out);
1580 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1581 I != E; ++I) {
1582 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1583 printVariableBody(GV);
1584 }
1585 }
1586
1587 void CppWriter::printFunctionHead(const Function* F) {
1588 nl(Out) << "Function* " << getCppName(F);
1589 if (is_inline) {
1590 Out << " = mod->getFunction(\"";
1591 printEscapedString(F->getName());
1592 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1593 nl(Out) << "if (!" << getCppName(F) << ") {";
1594 nl(Out) << getCppName(F);
1595 }
1596 Out<< " = Function::Create(";
1597 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1598 nl(Out) << "/*Linkage=*/";
1599 printLinkageType(F->getLinkage());
1600 Out << ",";
1601 nl(Out) << "/*Name=*/\"";
1602 printEscapedString(F->getName());
1603 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1604 nl(Out,-1);
1605 printCppName(F);
1606 Out << "->setCallingConv(";
1607 printCallingConv(F->getCallingConv());
1608 Out << ");";
1609 nl(Out);
1610 if (F->hasSection()) {
1611 printCppName(F);
1612 Out << "->setSection(\"" << F->getSection() << "\");";
1613 nl(Out);
1614 }
1615 if (F->getAlignment()) {
1616 printCppName(F);
1617 Out << "->setAlignment(" << F->getAlignment() << ");";
1618 nl(Out);
1619 }
1620 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1621 printCppName(F);
1622 Out << "->setVisibility(";
1623 printVisibilityType(F->getVisibility());
1624 Out << ");";
1625 nl(Out);
1626 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001627 if (F->hasGC()) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00001628 printCppName(F);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001629 Out << "->setGC(\"" << F->getGC() << "\");";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001630 nl(Out);
1631 }
1632 if (is_inline) {
1633 Out << "}";
1634 nl(Out);
1635 }
Devang Patel05988662008-09-25 21:00:45 +00001636 printAttributes(F->getAttributes(), getCppName(F));
Anton Korobeynikov50276522008-04-23 22:29:24 +00001637 printCppName(F);
Devang Patel05988662008-09-25 21:00:45 +00001638 Out << "->setAttributes(" << getCppName(F) << "_PAL);";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001639 nl(Out);
1640 }
1641
1642 void CppWriter::printFunctionBody(const Function *F) {
1643 if (F->isDeclaration())
1644 return; // external functions have no bodies.
1645
1646 // Clear the DefinedValues and ForwardRefs maps because we can't have
1647 // cross-function forward refs
1648 ForwardRefs.clear();
1649 DefinedValues.clear();
1650
1651 // Create all the argument values
1652 if (!is_inline) {
1653 if (!F->arg_empty()) {
1654 Out << "Function::arg_iterator args = " << getCppName(F)
1655 << "->arg_begin();";
1656 nl(Out);
1657 }
1658 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1659 AI != AE; ++AI) {
1660 Out << "Value* " << getCppName(AI) << " = args++;";
1661 nl(Out);
1662 if (AI->hasName()) {
1663 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1664 nl(Out);
1665 }
1666 }
1667 }
1668
1669 // Create all the basic blocks
1670 nl(Out);
1671 for (Function::const_iterator BI = F->begin(), BE = F->end();
1672 BI != BE; ++BI) {
1673 std::string bbname(getCppName(BI));
Owen Anderson267a0ff2009-08-14 17:41:33 +00001674 Out << "BasicBlock* " << bbname <<
1675 " = BasicBlock::Create(getGlobalContext(), \"";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001676 if (BI->hasName())
1677 printEscapedString(BI->getName());
1678 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1679 nl(Out);
1680 }
1681
1682 // Output all of its basic blocks... for the function
1683 for (Function::const_iterator BI = F->begin(), BE = F->end();
1684 BI != BE; ++BI) {
1685 std::string bbname(getCppName(BI));
1686 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1687 nl(Out);
1688
1689 // Output all of the instructions in the basic block...
1690 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1691 I != E; ++I) {
1692 printInstruction(I,bbname);
1693 }
1694 }
1695
1696 // Loop over the ForwardRefs and resolve them now that all instructions
1697 // are generated.
1698 if (!ForwardRefs.empty()) {
1699 nl(Out) << "// Resolve Forward References";
1700 nl(Out);
1701 }
1702
1703 while (!ForwardRefs.empty()) {
1704 ForwardRefMap::iterator I = ForwardRefs.begin();
1705 Out << I->second << "->replaceAllUsesWith("
1706 << getCppName(I->first) << "); delete " << I->second << ";";
1707 nl(Out);
1708 ForwardRefs.erase(I);
1709 }
1710 }
1711
1712 void CppWriter::printInline(const std::string& fname,
1713 const std::string& func) {
1714 const Function* F = TheModule->getFunction(func);
1715 if (!F) {
1716 error(std::string("Function '") + func + "' not found in input module");
1717 return;
1718 }
1719 if (F->isDeclaration()) {
1720 error(std::string("Function '") + func + "' is external!");
1721 return;
1722 }
1723 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1724 << getCppName(F);
1725 unsigned arg_count = 1;
1726 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1727 AI != AE; ++AI) {
1728 Out << ", Value* arg_" << arg_count;
1729 }
1730 Out << ") {";
1731 nl(Out);
1732 is_inline = true;
1733 printFunctionUses(F);
1734 printFunctionBody(F);
1735 is_inline = false;
1736 Out << "return " << getCppName(F->begin()) << ";";
1737 nl(Out) << "}";
1738 nl(Out);
1739 }
1740
1741 void CppWriter::printModuleBody() {
1742 // Print out all the type definitions
1743 nl(Out) << "// Type Definitions"; nl(Out);
1744 printTypes(TheModule);
1745
1746 // Functions can call each other and global variables can reference them so
1747 // define all the functions first before emitting their function bodies.
1748 nl(Out) << "// Function Declarations"; nl(Out);
1749 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1750 I != E; ++I)
1751 printFunctionHead(I);
1752
1753 // Process the global variables declarations. We can't initialze them until
1754 // after the constants are printed so just print a header for each global
1755 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1756 for (Module::const_global_iterator I = TheModule->global_begin(),
1757 E = TheModule->global_end(); I != E; ++I) {
1758 printVariableHead(I);
1759 }
1760
1761 // Print out all the constants definitions. Constants don't recurse except
1762 // through GlobalValues. All GlobalValues have been declared at this point
1763 // so we can proceed to generate the constants.
1764 nl(Out) << "// Constant Definitions"; nl(Out);
1765 printConstants(TheModule);
1766
1767 // Process the global variables definitions now that all the constants have
1768 // been emitted. These definitions just couple the gvars with their constant
1769 // initializers.
1770 nl(Out) << "// Global Variable Definitions"; nl(Out);
1771 for (Module::const_global_iterator I = TheModule->global_begin(),
1772 E = TheModule->global_end(); I != E; ++I) {
1773 printVariableBody(I);
1774 }
1775
1776 // Finally, we can safely put out all of the function bodies.
1777 nl(Out) << "// Function Definitions"; nl(Out);
1778 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1779 I != E; ++I) {
1780 if (!I->isDeclaration()) {
1781 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1782 << ")";
1783 nl(Out) << "{";
1784 nl(Out,1);
1785 printFunctionBody(I);
1786 nl(Out,-1) << "}";
1787 nl(Out);
1788 }
1789 }
1790 }
1791
1792 void CppWriter::printProgram(const std::string& fname,
1793 const std::string& mName) {
Owen Anderson267a0ff2009-08-14 17:41:33 +00001794 Out << "#include <llvm/LLVMContext.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001795 Out << "#include <llvm/Module.h>\n";
1796 Out << "#include <llvm/DerivedTypes.h>\n";
1797 Out << "#include <llvm/Constants.h>\n";
1798 Out << "#include <llvm/GlobalVariable.h>\n";
1799 Out << "#include <llvm/Function.h>\n";
1800 Out << "#include <llvm/CallingConv.h>\n";
1801 Out << "#include <llvm/BasicBlock.h>\n";
1802 Out << "#include <llvm/Instructions.h>\n";
1803 Out << "#include <llvm/InlineAsm.h>\n";
David Greene71847812009-07-14 20:18:05 +00001804 Out << "#include <llvm/Support/FormattedStream.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001805 Out << "#include <llvm/Support/MathExtras.h>\n";
1806 Out << "#include <llvm/Pass.h>\n";
1807 Out << "#include <llvm/PassManager.h>\n";
Nicolas Geoffray9474ede2008-05-14 07:52:03 +00001808 Out << "#include <llvm/ADT/SmallVector.h>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001809 Out << "#include <llvm/Analysis/Verifier.h>\n";
1810 Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1811 Out << "#include <algorithm>\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001812 Out << "using namespace llvm;\n\n";
1813 Out << "Module* " << fname << "();\n\n";
1814 Out << "int main(int argc, char**argv) {\n";
1815 Out << " Module* Mod = " << fname << "();\n";
1816 Out << " verifyModule(*Mod, PrintMessageAction);\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001817 Out << " PassManager PM;\n";
Dan Gohmanf9231292008-12-08 07:07:24 +00001818 Out << " PM.add(createPrintModulePass(&outs()));\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001819 Out << " PM.run(*Mod);\n";
1820 Out << " return 0;\n";
1821 Out << "}\n\n";
1822 printModule(fname,mName);
1823 }
1824
1825 void CppWriter::printModule(const std::string& fname,
1826 const std::string& mName) {
1827 nl(Out) << "Module* " << fname << "() {";
1828 nl(Out,1) << "// Module Construction";
Nick Lewyckyb8b73472009-06-26 04:33:37 +00001829 nl(Out) << "Module* mod = new Module(\"";
1830 printEscapedString(mName);
Owen Anderson267a0ff2009-08-14 17:41:33 +00001831 Out << "\", getGlobalContext());";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001832 if (!TheModule->getTargetTriple().empty()) {
1833 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1834 }
1835 if (!TheModule->getTargetTriple().empty()) {
1836 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1837 << "\");";
1838 }
1839
1840 if (!TheModule->getModuleInlineAsm().empty()) {
1841 nl(Out) << "mod->setModuleInlineAsm(\"";
1842 printEscapedString(TheModule->getModuleInlineAsm());
1843 Out << "\");";
1844 }
1845 nl(Out);
1846
1847 // Loop over the dependent libraries and emit them.
1848 Module::lib_iterator LI = TheModule->lib_begin();
1849 Module::lib_iterator LE = TheModule->lib_end();
1850 while (LI != LE) {
1851 Out << "mod->addLibrary(\"" << *LI << "\");";
1852 nl(Out);
1853 ++LI;
1854 }
1855 printModuleBody();
1856 nl(Out) << "return mod;";
1857 nl(Out,-1) << "}";
1858 nl(Out);
1859 }
1860
1861 void CppWriter::printContents(const std::string& fname,
1862 const std::string& mName) {
1863 Out << "\nModule* " << fname << "(Module *mod) {\n";
Nick Lewyckyb8b73472009-06-26 04:33:37 +00001864 Out << "\nmod->setModuleIdentifier(\"";
1865 printEscapedString(mName);
1866 Out << "\");\n";
Anton Korobeynikov50276522008-04-23 22:29:24 +00001867 printModuleBody();
1868 Out << "\nreturn mod;\n";
1869 Out << "\n}\n";
1870 }
1871
1872 void CppWriter::printFunction(const std::string& fname,
1873 const std::string& funcName) {
1874 const Function* F = TheModule->getFunction(funcName);
1875 if (!F) {
1876 error(std::string("Function '") + funcName + "' not found in input module");
1877 return;
1878 }
1879 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1880 printFunctionUses(F);
1881 printFunctionHead(F);
1882 printFunctionBody(F);
1883 Out << "return " << getCppName(F) << ";\n";
1884 Out << "}\n";
1885 }
1886
1887 void CppWriter::printFunctions() {
1888 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1889 Module::const_iterator I = funcs.begin();
1890 Module::const_iterator IE = funcs.end();
1891
1892 for (; I != IE; ++I) {
1893 const Function &func = *I;
1894 if (!func.isDeclaration()) {
1895 std::string name("define_");
1896 name += func.getName();
1897 printFunction(name, func.getName());
1898 }
1899 }
1900 }
1901
1902 void CppWriter::printVariable(const std::string& fname,
1903 const std::string& varName) {
1904 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1905
1906 if (!GV) {
1907 error(std::string("Variable '") + varName + "' not found in input module");
1908 return;
1909 }
1910 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1911 printVariableUses(GV);
1912 printVariableHead(GV);
1913 printVariableBody(GV);
1914 Out << "return " << getCppName(GV) << ";\n";
1915 Out << "}\n";
1916 }
1917
1918 void CppWriter::printType(const std::string& fname,
1919 const std::string& typeName) {
1920 const Type* Ty = TheModule->getTypeByName(typeName);
1921 if (!Ty) {
1922 error(std::string("Type '") + typeName + "' not found in input module");
1923 return;
1924 }
1925 Out << "\nType* " << fname << "(Module *mod) {\n";
1926 printType(Ty);
1927 Out << "return " << getCppName(Ty) << ";\n";
1928 Out << "}\n";
1929 }
1930
1931 bool CppWriter::runOnModule(Module &M) {
1932 TheModule = &M;
1933
1934 // Emit a header
1935 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1936
1937 // Get the name of the function we're supposed to generate
1938 std::string fname = FuncName.getValue();
1939
1940 // Get the name of the thing we are to generate
1941 std::string tgtname = NameToGenerate.getValue();
1942 if (GenerationType == GenModule ||
1943 GenerationType == GenContents ||
1944 GenerationType == GenProgram ||
1945 GenerationType == GenFunctions) {
1946 if (tgtname == "!bad!") {
1947 if (M.getModuleIdentifier() == "-")
1948 tgtname = "<stdin>";
1949 else
1950 tgtname = M.getModuleIdentifier();
1951 }
1952 } else if (tgtname == "!bad!")
1953 error("You must use the -for option with -gen-{function,variable,type}");
1954
1955 switch (WhatToGenerate(GenerationType)) {
1956 case GenProgram:
1957 if (fname.empty())
1958 fname = "makeLLVMModule";
1959 printProgram(fname,tgtname);
1960 break;
1961 case GenModule:
1962 if (fname.empty())
1963 fname = "makeLLVMModule";
1964 printModule(fname,tgtname);
1965 break;
1966 case GenContents:
1967 if (fname.empty())
1968 fname = "makeLLVMModuleContents";
1969 printContents(fname,tgtname);
1970 break;
1971 case GenFunction:
1972 if (fname.empty())
1973 fname = "makeLLVMFunction";
1974 printFunction(fname,tgtname);
1975 break;
1976 case GenFunctions:
1977 printFunctions();
1978 break;
1979 case GenInline:
1980 if (fname.empty())
1981 fname = "makeLLVMInline";
1982 printInline(fname,tgtname);
1983 break;
1984 case GenVariable:
1985 if (fname.empty())
1986 fname = "makeLLVMVariable";
1987 printVariable(fname,tgtname);
1988 break;
1989 case GenType:
1990 if (fname.empty())
1991 fname = "makeLLVMType";
1992 printType(fname,tgtname);
1993 break;
1994 default:
1995 error("Invalid generation option");
1996 }
1997
1998 return false;
1999 }
2000}
2001
2002char CppWriter::ID = 0;
2003
2004//===----------------------------------------------------------------------===//
2005// External Interface declaration
2006//===----------------------------------------------------------------------===//
2007
2008bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
David Greene71847812009-07-14 20:18:05 +00002009 formatted_raw_ostream &o,
Anton Korobeynikov50276522008-04-23 22:29:24 +00002010 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00002011 CodeGenOpt::Level OptLevel) {
Anton Korobeynikov50276522008-04-23 22:29:24 +00002012 if (FileType != TargetMachine::AssemblyFile) return true;
2013 PM.add(new CppWriter(o));
2014 return false;
2015}