llvm.org GIT mirror llvm / a9d9ca4
Drop llvm2cpp, it's now a llc target git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@50614 91177308-0d34-0410-b5e6-96231b3b80d8 Anton Korobeynikov 11 years ago
5 changed file(s) with 0 addition(s) and 2340 deletion(s). Raw diff Collapse all Expand all
+0
-217
docs/CommandGuide/llvm2cpp.pod less more
None =pod
1
2 =head1 NAME
3
4 llvm2xpp - LLVM bitcode to LLVM C++ IR translator
5
6 =head1 SYNOPSIS
7
8 B [I] [I]
9
10 =head1 DESCRIPTION
11
12 B translates from LLVM bitcode (.bc files) to a
13 corresponding C++ source file that will make calls against the LLVM C++ API to
14 build the same module as the input. By default, the C++ output is a complete
15 program that builds the module, verifies it and then emits the module as
16 LLVM assembly. This technique assists with testing because the input to
17 B and the output of the generated C++ program should be identical.
18
19 If F is omitted or is C<->, then B reads its input from
20 standard input.
21
22 If an output file is not specified with the B<-o> option, then
23 B sends its output to a file or standard output by following
24 these rules:
25
26 =over
27
28 =item *
29
30 If the input is standard input, then the output is standard output.
31
32 =item *
33
34 If the input is a file that ends with C<.bc>, then the output file is of
35 the same name, except that the suffix is changed to C<.cpp>.
36
37 =item *
38
39 If the input is a file that does not end with the C<.bc> suffix, then the
40 output file has the same name as the input file, except that the C<.cpp>
41 suffix is appended.
42
43 =back
44
45 =head1 OPTIONS
46
47 =over
48
49 =item B<-f>
50
51 Force overwrite. Normally, B will refuse to overwrite an
52 output file that already exists. With this option, B
53 will overwrite the output file and replace it with new C++ source code.
54
55 =item B<--help>
56
57 Print a summary of command line options.
58
59 =item B<-f>
60
61 Normally, B will not overwrite an existing output file. With this
62 option, that default behavior is changed and the program will overwrite existing
63 output files.
64
65 =item B<-o> F
66
67 Specify the output file name. If F is C<->, then B
68 sends its output to standard output.
69
70 =item B<-funcname> F
71
72 Specify the name of the function to be generated. The generated code contains a
73 single function that produces the input module. By default its name is
74 I. The B<-funcname> option overrides this default and allows
75 you to control the name of the generated function. This is handy in conjunction
76 with the B<-fragment> option when you only want B to generate a
77 single function that produces the module. With both options, such generated code
78 could be I<#included> into another program.
79
80 =item B<-for>
81
82 Specify the name of the thing for which C++ code should be generated. By default
83 the entire input module is re-generated. However, use of the various B<-gen-*>
84 options can restrict what is produced. This option indicates what that
85 restriction is.
86
87 =item B<-gen-program>
88
89 Specify that the output should be a complete program. Such program will recreate
90 B's input as an LLVM module, verify that module, and then write out
91 the module in LLVM assembly format. This is useful for doing identity tests
92 where the output of the generated program is identical to the input to
93 B. The LLVM DejaGnu test suite can make use of this fact. This is the
94 default form of generated output.
95
96 If the B<-for> option is given with this option, it specifies the module
97 identifier to use for the module created.
98
99 =item B<-gen-module>
100
101 Specify that the output should be a function that regenerates the module. It is
102 assumed that this output will be #included into another program that has already
103 arranged for the correct header files to be #included. The function generated
104 takes no arguments and returns a I.
105
106 If the B<-for> option is given with this option, it specifies the module
107 identifier to use in creating the module returned by the generated function.
108
109 =item B<-gen-contents>
110
111 Specify that the output should be a function that adds the contents of the input
112 module to another module. It is assumed that the output will be #included into
113 another program that has already arranged for the correct header files to be
114 #included. The function generated takes a single argument of type I and
115 returns that argument. Note that Module level attributes such as endianess,
116 pointer size, target triple and inline asm are not passed on from the input
117 module to the destination module. Only the sub-elements of the module (types,
118 constants, functions, global variables) will be added to the input module.
119
120 If the B<-for> option is given with this option, it specifies the module
121 identifier to set in the input module by the generated function.
122
123 =item B<-gen-function>
124
125 Specify that the output should be a function that produces the definitions
126 necessary for a specific function to be added to a module. It is assumed that
127 the output will be #included into another program that has already arranged
128 for the correct header files to be #included. The function generated takes a
129 single argument of type I and returns the I that it added to
130 the module. Note that only those things (types, constants, etc.) directly
131 needed in the definition of the function will be placed in the generated
132 function.
133
134 The B<-for> option must be given with this option or an error will be produced.
135 The value of the option must be the name of a function in the input module for
136 which code should be generated. If the named function does not exist an error
137 will be produced.
138
139 =item B<-gen-inline>
140
141 This option is very analagous to B<-gen-function> except that the generated
142 function will not re-produce the target function's definition. Instead, the body
143 of the target function is inserted into some other function passed as an
144 argument to the generated function. Similarly any arguments to the function must
145 be passed to the generated function. The result of the generated function is the
146 first basic block of the target function.
147
148 The B<-for> option works the same way as it does for B<-gen-function>.
149
150 =item B<-gen-variable>
151
152 Specify that the output should be a function that produces the definitions
153 necessary for a specific global variable to be added to a module. It is assumed
154 that the output will be #included into another program that has already arranged
155 for the correct header files to be #included. The function generated takes a
156 single argument of type I and returns the I that it
157 added to the module. Note that only those things (types, constants, etc.)
158 directly needed in the definition of the global variable will be placed in the
159 generated function.
160
161 The B<-for> option must be given with this option or an error will be produced.
162 THe value of the option must be the name of a global variable in the input
163 module for which code should be generated. If the named global variable does not
164 exist an error will be produced.
165
166 =item B<-gen-type>
167
168 Specify that the output should be a function that produces the definitions
169 necessary for specific type to be added to a module. It is assumed that the
170 otuput will be #included into another program that has already arranged for the
171 correct header files to be #included. The function generated take a single
172 argument of type I and returns the I that it added to the
173 module. Note that the generated function will only add the necessary type
174 definitions to (possibly recursively) define the requested type.
175
176 The B<-for> option must be given with this option or an error will be produced.
177 The value of the option must be the name of a global type in the input module
178 for which code should be generated. If the named type does not exist an error
179 will be produced.
180
181 =item B<-stats>
182
183 Show pass statistics (not interesting in this program).
184
185 =item B<-time-passes>
186
187 Show pass timing statistics (not interesting in this program).
188
189 =item B<-version>
190
191 Show the version number of this program.
192
193 =back
194
195
196 =head1 EXIT STATUS
197
198 If B succeeds, it will exit with 0. Otherwise, if an error
199 occurs, it will exit with a non-zero value.
200
201 =head1 SEE ALSO
202
203 L L
204
205 =head1 NOTES
206
207 This tool may be removed from a future version of LLVM. Instead, its
208 functionality may be incorporated into the llc tool. It would then act similarly
209 to other targets except its output would be C++ source that could be compiled to
210 construct the input program.
211
212 =head1 AUTHORS
213
214 Written by Reid Spencer (L).
215
216 =cut
+0
-1968
tools/llvm2cpp/CppWriter.cpp less more
None //===-- CppWriter.cpp - Printing LLVM IR as a C++ Source File -------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the writing of the LLVM IR as a set of C++ calls to the
10 // LLVM IR interface. The input module is assumed to be verified.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CallingConv.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instruction.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/TypeSymbolTable.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Config/config.h"
30 #include
31 #include
32 #include
33
34 using namespace llvm;
35
36 static cl::opt
37 FuncName("funcname", cl::desc("Specify the name of the generated function"),
38 cl::value_desc("function name"));
39
40 enum WhatToGenerate {
41 GenProgram,
42 GenModule,
43 GenContents,
44 GenFunction,
45 GenFunctions,
46 GenInline,
47 GenVariable,
48 GenType
49 };
50
51 static cl::opt GenerationType(cl::Optional,
52 cl::desc("Choose what kind of output to generate"),
53 cl::init(GenProgram),
54 cl::values(
55 clEnumValN(GenProgram, "gen-program", "Generate a complete program"),
56 clEnumValN(GenModule, "gen-module", "Generate a module definition"),
57 clEnumValN(GenContents, "gen-contents", "Generate contents of a module"),
58 clEnumValN(GenFunction, "gen-function", "Generate a function definition"),
59 clEnumValN(GenFunctions,"gen-functions", "Generate all function definitions"),
60 clEnumValN(GenInline, "gen-inline", "Generate an inline function"),
61 clEnumValN(GenVariable, "gen-variable", "Generate a variable definition"),
62 clEnumValN(GenType, "gen-type", "Generate a type definition"),
63 clEnumValEnd
64 )
65 );
66
67 static cl::opt NameToGenerate("for", cl::Optional,
68 cl::desc("Specify the name of the thing to generate"),
69 cl::init("!bad!"));
70
71 namespace {
72 typedef std::vector TypeList;
73 typedef std::map TypeMap;
74 typedef std::map ValueMap;
75 typedef std::set NameSet;
76 typedef std::set TypeSet;
77 typedef std::set ValueSet;
78 typedef std::map ForwardRefMap;
79
80 class CppWriter {
81 const char* progname;
82 std::ostream &Out;
83 const Module *TheModule;
84 uint64_t uniqueNum;
85 TypeMap TypeNames;
86 ValueMap ValueNames;
87 TypeMap UnresolvedTypes;
88 TypeList TypeStack;
89 NameSet UsedNames;
90 TypeSet DefinedTypes;
91 ValueSet DefinedValues;
92 ForwardRefMap ForwardRefs;
93 bool is_inline;
94
95 public:
96 inline CppWriter(std::ostream &o, const Module *M, const char* pn="llvm2cpp")
97 : progname(pn), Out(o), TheModule(M), uniqueNum(0), TypeNames(),
98 ValueNames(), UnresolvedTypes(), TypeStack(), is_inline(false) { }
99
100 const Module* getModule() { return TheModule; }
101
102 void printProgram(const std::string& fname, const std::string& modName );
103 void printModule(const std::string& fname, const std::string& modName );
104 void printContents(const std::string& fname, const std::string& modName );
105 void printFunction(const std::string& fname, const std::string& funcName );
106 void printFunctions();
107 void printInline(const std::string& fname, const std::string& funcName );
108 void printVariable(const std::string& fname, const std::string& varName );
109 void printType(const std::string& fname, const std::string& typeName );
110
111 void error(const std::string& msg);
112
113 private:
114 void printLinkageType(GlobalValue::LinkageTypes LT);
115 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
116 void printCallingConv(unsigned cc);
117 void printEscapedString(const std::string& str);
118 void printCFP(const ConstantFP* CFP);
119
120 std::string getCppName(const Type* val);
121 inline void printCppName(const Type* val);
122
123 std::string getCppName(const Value* val);
124 inline void printCppName(const Value* val);
125
126 void printParamAttrs(const PAListPtr &PAL, const std::string &name);
127 bool printTypeInternal(const Type* Ty);
128 inline void printType(const Type* Ty);
129 void printTypes(const Module* M);
130
131 void printConstant(const Constant *CPV);
132 void printConstants(const Module* M);
133
134 void printVariableUses(const GlobalVariable *GV);
135 void printVariableHead(const GlobalVariable *GV);
136 void printVariableBody(const GlobalVariable *GV);
137
138 void printFunctionUses(const Function *F);
139 void printFunctionHead(const Function *F);
140 void printFunctionBody(const Function *F);
141 void printInstruction(const Instruction *I, const std::string& bbname);
142 std::string getOpName(Value*);
143
144 void printModuleBody();
145
146 };
147
148 static unsigned indent_level = 0;
149 inline std::ostream& nl(std::ostream& Out, int delta = 0) {
150 Out << "\n";
151 if (delta >= 0 || indent_level >= unsigned(-delta))
152 indent_level += delta;
153 for (unsigned i = 0; i < indent_level; ++i)
154 Out << " ";
155 return Out;
156 }
157
158 inline void in() { indent_level++; }
159 inline void out() { if (indent_level >0) indent_level--; }
160
161 inline void
162 sanitize(std::string& str) {
163 for (size_t i = 0; i < str.length(); ++i)
164 if (!isalnum(str[i]) && str[i] != '_')
165 str[i] = '_';
166 }
167
168 inline std::string
169 getTypePrefix(const Type* Ty ) {
170 switch (Ty->getTypeID()) {
171 case Type::VoidTyID: return "void_";
172 case Type::IntegerTyID:
173 return std::string("int") + utostr(cast(Ty)->getBitWidth()) +
174 "_";
175 case Type::FloatTyID: return "float_";
176 case Type::DoubleTyID: return "double_";
177 case Type::LabelTyID: return "label_";
178 case Type::FunctionTyID: return "func_";
179 case Type::StructTyID: return "struct_";
180 case Type::ArrayTyID: return "array_";
181 case Type::PointerTyID: return "ptr_";
182 case Type::VectorTyID: return "packed_";
183 case Type::OpaqueTyID: return "opaque_";
184 default: return "other_";
185 }
186 return "unknown_";
187 }
188
189 // Looks up the type in the symbol table and returns a pointer to its name or
190 // a null pointer if it wasn't found. Note that this isn't the same as the
191 // Mode::getTypeName function which will return an empty string, not a null
192 // pointer if the name is not found.
193 inline const std::string*
194 findTypeName(const TypeSymbolTable& ST, const Type* Ty)
195 {
196 TypeSymbolTable::const_iterator TI = ST.begin();
197 TypeSymbolTable::const_iterator TE = ST.end();
198 for (;TI != TE; ++TI)
199 if (TI->second == Ty)
200 return &(TI->first);
201 return 0;
202 }
203
204 void
205 CppWriter::error(const std::string& msg) {
206 std::cerr << progname << ": " << msg << "\n";
207 exit(2);
208 }
209
210 // printCFP - Print a floating point constant .. very carefully :)
211 // This makes sure that conversion to/from floating yields the same binary
212 // result so that we don't lose precision.
213 void
214 CppWriter::printCFP(const ConstantFP *CFP) {
215 APFloat APF = APFloat(CFP->getValueAPF()); // copy
216 if (CFP->getType() == Type::FloatTy)
217 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
218 Out << "ConstantFP::get(";
219 if (CFP->getType() == Type::DoubleTy)
220 Out << "Type::DoubleTy, ";
221 else
222 Out << "Type::FloatTy, ";
223 Out << "APFloat(";
224 #if HAVE_PRINTF_A
225 char Buffer[100];
226 sprintf(Buffer, "%A", APF.convertToDouble());
227 if ((!strncmp(Buffer, "0x", 2) ||
228 !strncmp(Buffer, "-0x", 3) ||
229 !strncmp(Buffer, "+0x", 3)) &&
230 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
231 if (CFP->getType() == Type::DoubleTy)
232 Out << "BitsToDouble(" << Buffer << ")";
233 else
234 Out << "BitsToFloat((float)" << Buffer << ")";
235 Out << ")";
236 } else {
237 #endif
238 std::string StrVal = ftostr(CFP->getValueAPF());
239
240 while (StrVal[0] == ' ')
241 StrVal.erase(StrVal.begin());
242
243 // Check to make sure that the stringized number is not some string like
244 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex.
245 if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
246 ((StrVal[0] == '-' || StrVal[0] == '+') &&
247 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
248 (CFP->isExactlyValue(atof(StrVal.c_str())))) {
249 if (CFP->getType() == Type::DoubleTy)
250 Out << StrVal;
251 else
252 Out << StrVal << "f";
253 }
254 else if (CFP->getType() == Type::DoubleTy)
255 Out << "BitsToDouble(0x" << std::hex
256 << CFP->getValueAPF().convertToAPInt().getZExtValue()
257 << std::dec << "ULL) /* " << StrVal << " */";
258 else
259 Out << "BitsToFloat(0x" << std::hex
260 << (uint32_t)CFP->getValueAPF().convertToAPInt().getZExtValue()
261 << std::dec << "U) /* " << StrVal << " */";
262 Out << ")";
263 #if HAVE_PRINTF_A
264 }
265 #endif
266 Out << ")";
267 }
268
269 void
270 CppWriter::printCallingConv(unsigned 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
281 void
282 CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
283 switch (LT) {
284 case GlobalValue::InternalLinkage:
285 Out << "GlobalValue::InternalLinkage"; break;
286 case GlobalValue::LinkOnceLinkage:
287 Out << "GlobalValue::LinkOnceLinkage "; break;
288 case GlobalValue::WeakLinkage:
289 Out << "GlobalValue::WeakLinkage"; break;
290 case GlobalValue::AppendingLinkage:
291 Out << "GlobalValue::AppendingLinkage"; break;
292 case GlobalValue::ExternalLinkage:
293 Out << "GlobalValue::ExternalLinkage"; break;
294 case GlobalValue::DLLImportLinkage:
295 Out << "GlobalValue::DLLImportLinkage"; break;
296 case GlobalValue::DLLExportLinkage:
297 Out << "GlobalValue::DLLExportLinkage"; break;
298 case GlobalValue::ExternalWeakLinkage:
299 Out << "GlobalValue::ExternalWeakLinkage"; break;
300 case GlobalValue::GhostLinkage:
301 Out << "GlobalValue::GhostLinkage"; break;
302 }
303 }
304
305 void
306 CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
307 switch (VisType) {
308 default: assert(0 && "Unknown GVar visibility");
309 case GlobalValue::DefaultVisibility:
310 Out << "GlobalValue::DefaultVisibility";
311 break;
312 case GlobalValue::HiddenVisibility:
313 Out << "GlobalValue::HiddenVisibility";
314 break;
315 case GlobalValue::ProtectedVisibility:
316 Out << "GlobalValue::ProtectedVisibility";
317 break;
318 }
319 }
320
321 // printEscapedString - Print each character of the specified string, escaping
322 // it if it is not printable or if it is an escape char.
323 void
324 CppWriter::printEscapedString(const std::string &Str) {
325 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
326 unsigned char C = Str[i];
327 if (isprint(C) && C != '"' && C != '\\') {
328 Out << C;
329 } else {
330 Out << "\\x"
331 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
332 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
333 }
334 }
335 }
336
337 std::string
338 CppWriter::getCppName(const Type* Ty)
339 {
340 // First, handle the primitive types .. easy
341 if (Ty->isPrimitiveType() || Ty->isInteger()) {
342 switch (Ty->getTypeID()) {
343 case Type::VoidTyID: return "Type::VoidTy";
344 case Type::IntegerTyID: {
345 unsigned BitWidth = cast(Ty)->getBitWidth();
346 return "IntegerType::get(" + utostr(BitWidth) + ")";
347 }
348 case Type::FloatTyID: return "Type::FloatTy";
349 case Type::DoubleTyID: return "Type::DoubleTy";
350 case Type::LabelTyID: return "Type::LabelTy";
351 default:
352 error("Invalid primitive type");
353 break;
354 }
355 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
356 }
357
358 // Now, see if we've seen the type before and return that
359 TypeMap::iterator I = TypeNames.find(Ty);
360 if (I != TypeNames.end())
361 return I->second;
362
363 // Okay, let's build a new name for this type. Start with a prefix
364 const char* prefix = 0;
365 switch (Ty->getTypeID()) {
366 case Type::FunctionTyID: prefix = "FuncTy_"; break;
367 case Type::StructTyID: prefix = "StructTy_"; break;
368 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
369 case Type::PointerTyID: prefix = "PointerTy_"; break;
370 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
371 case Type::VectorTyID: prefix = "VectorTy_"; break;
372 default: prefix = "OtherTy_"; break; // prevent breakage
373 }
374
375 // See if the type has a name in the symboltable and build accordingly
376 const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
377 std::string name;
378 if (tName)
379 name = std::string(prefix) + *tName;
380 else
381 name = std::string(prefix) + utostr(uniqueNum++);
382 sanitize(name);
383
384 // Save the name
385 return TypeNames[Ty] = name;
386 }
387
388 void
389 CppWriter::printCppName(const Type* Ty)
390 {
391 printEscapedString(getCppName(Ty));
392 }
393
394 std::string
395 CppWriter::getCppName(const Value* val) {
396 std::string name;
397 ValueMap::iterator I = ValueNames.find(val);
398 if (I != ValueNames.end() && I->first == val)
399 return I->second;
400
401 if (const GlobalVariable* GV = dyn_cast(val)) {
402 name = std::string("gvar_") +
403 getTypePrefix(GV->getType()->getElementType());
404 } else if (isa(val)) {
405 name = std::string("func_");
406 } else if (const Constant* C = dyn_cast(val)) {
407 name = std::string("const_") + getTypePrefix(C->getType());
408 } else if (const Argument* Arg = dyn_cast(val)) {
409 if (is_inline) {
410 unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
411 Function::const_arg_iterator(Arg)) + 1;
412 name = std::string("arg_") + utostr(argNum);
413 NameSet::iterator NI = UsedNames.find(name);
414 if (NI != UsedNames.end())
415 name += std::string("_") + utostr(uniqueNum++);
416 UsedNames.insert(name);
417 return ValueNames[val] = name;
418 } else {
419 name = getTypePrefix(val->getType());
420 }
421 } else {
422 name = getTypePrefix(val->getType());
423 }
424 name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
425 sanitize(name);
426 NameSet::iterator NI = UsedNames.find(name);
427 if (NI != UsedNames.end())
428 name += std::string("_") + utostr(uniqueNum++);
429 UsedNames.insert(name);
430 return ValueNames[val] = name;
431 }
432
433 void
434 CppWriter::printCppName(const Value* val) {
435 printEscapedString(getCppName(val));
436 }
437
438 void
439 CppWriter::printParamAttrs(const PAListPtr &PAL, const std::string &name) {
440 Out << "PAListPtr " << name << "_PAL = 0;";
441 nl(Out);
442 if (!PAL.isEmpty()) {
443 Out << '{'; in(); nl(Out);
444 Out << "SmallVector Attrs;"; nl(Out);
445 Out << "ParamAttrsWithIndex PAWI;"; nl(Out);
446 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
447 uint16_t index = PAL.getSlot(i).Index;
448 ParameterAttributes attrs = PAL.getSlot(i).Attrs;
449 Out << "PAWI.index = " << index << "; PAWI.attrs = 0 ";
450 if (attrs & ParamAttr::SExt)
451 Out << " | ParamAttr::SExt";
452 if (attrs & ParamAttr::ZExt)
453 Out << " | ParamAttr::ZExt";
454 if (attrs & ParamAttr::StructRet)
455 Out << " | ParamAttr::StructRet";
456 if (attrs & ParamAttr::InReg)
457 Out << " | ParamAttr::InReg";
458 if (attrs & ParamAttr::NoReturn)
459 Out << " | ParamAttr::NoReturn";
460 if (attrs & ParamAttr::NoUnwind)
461 Out << " | ParamAttr::NoUnwind";
462 if (attrs & ParamAttr::ByVal)
463 Out << " | ParamAttr::ByVal";
464 if (attrs & ParamAttr::NoAlias)
465 Out << " | ParamAttr::NoAlias";
466 if (attrs & ParamAttr::Nest)
467 Out << " | ParamAttr::Nest";
468 if (attrs & ParamAttr::ReadNone)
469 Out << " | ParamAttr::ReadNone";
470 if (attrs & ParamAttr::ReadOnly)
471 Out << " | ParamAttr::ReadOnly";
472 Out << ";";
473 nl(Out);
474 Out << "Attrs.push_back(PAWI);";
475 nl(Out);
476 }
477 Out << name << "_PAL = PAListPtr::get(Attrs.begin(), Attrs.end());";
478 nl(Out);
479 out(); nl(Out);
480 Out << '}'; nl(Out);
481 }
482 }
483
484 bool
485 CppWriter::printTypeInternal(const Type* Ty) {
486 // We don't print definitions for primitive types
487 if (Ty->isPrimitiveType() || Ty->isInteger())
488 return false;
489
490 // If we already defined this type, we don't need to define it again.
491 if (DefinedTypes.find(Ty) != DefinedTypes.end())
492 return false;
493
494 // Everything below needs the name for the type so get it now.
495 std::string typeName(getCppName(Ty));
496
497 // Search the type stack for recursion. If we find it, then generate this
498 // as an OpaqueType, but make sure not to do this multiple times because
499 // the type could appear in multiple places on the stack. Once the opaque
500 // definition is issued, it must not be re-issued. Consequently we have to
501 // check the UnresolvedTypes list as well.
502 TypeList::const_iterator TI = std::find(TypeStack.begin(),TypeStack.end(),Ty);
503 if (TI != TypeStack.end()) {
504 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
505 if (I == UnresolvedTypes.end()) {
506 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
507 nl(Out);
508 UnresolvedTypes[Ty] = typeName;
509 }
510 return true;
511 }
512
513 // We're going to print a derived type which, by definition, contains other
514 // types. So, push this one we're printing onto the type stack to assist with
515 // recursive definitions.
516 TypeStack.push_back(Ty);
517
518 // Print the type definition
519 switch (Ty->getTypeID()) {
520 case Type::FunctionTyID: {
521 const FunctionType* FT = cast(Ty);
522 Out << "std::vector" << typeName << "_args;";
523 nl(Out);
524 FunctionType::param_iterator PI = FT->param_begin();
525 FunctionType::param_iterator PE = FT->param_end();
526 for (; PI != PE; ++PI) {
527 const Type* argTy = static_cast(*PI);
528 bool isForward = printTypeInternal(argTy);
529 std::string argName(getCppName(argTy));
530 Out << typeName << "_args.push_back(" << argName;
531 if (isForward)
532 Out << "_fwd";
533 Out << ");";
534 nl(Out);
535 }
536 bool isForward = printTypeInternal(FT->getReturnType());
537 std::string retTypeName(getCppName(FT->getReturnType()));
538 Out << "FunctionType* " << typeName << " = FunctionType::get(";
539 in(); nl(Out) << "/*Result=*/" << retTypeName;
540 if (isForward)
541 Out << "_fwd";
542 Out << ",";
543 nl(Out) << "/*Params=*/" << typeName << "_args,";
544 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
545 out();
546 nl(Out);
547 break;
548 }
549 case Type::StructTyID: {
550 const StructType* ST = cast(Ty);
551 Out << "std::vector" << typeName << "_fields;";
552 nl(Out);
553 StructType::element_iterator EI = ST->element_begin();
554 StructType::element_iterator EE = ST->element_end();
555 for (; EI != EE; ++EI) {
556 const Type* fieldTy = static_cast(*EI);
557 bool isForward = printTypeInternal(fieldTy);
558 std::string fieldName(getCppName(fieldTy));
559 Out << typeName << "_fields.push_back(" << fieldName;
560 if (isForward)
561 Out << "_fwd";
562 Out << ");";
563 nl(Out);
564 }
565 Out << "StructType* " << typeName << " = StructType::get("
566 << typeName << "_fields, /*isPacked=*/"
567 << (ST->isPacked() ? "true" : "false") << ");";
568 nl(Out);
569 break;
570 }
571 case Type::ArrayTyID: {
572 const ArrayType* AT = cast(Ty);
573 const Type* ET = AT->getElementType();
574 bool isForward = printTypeInternal(ET);
575 std::string elemName(getCppName(ET));
576 Out << "ArrayType* " << typeName << " = ArrayType::get("
577 << elemName << (isForward ? "_fwd" : "")
578 << ", " << utostr(AT->getNumElements()) << ");";
579 nl(Out);
580 break;
581 }
582 case Type::PointerTyID: {
583 const PointerType* PT = cast(Ty);
584 const Type* ET = PT->getElementType();
585 bool isForward = printTypeInternal(ET);
586 std::string elemName(getCppName(ET));
587 Out << "PointerType* " << typeName << " = PointerType::get("
588 << elemName << (isForward ? "_fwd" : "")
589 << ", " << utostr(PT->getAddressSpace()) << ");";
590 nl(Out);
591 break;
592 }
593 case Type::VectorTyID: {
594 const VectorType* PT = cast(Ty);
595 const Type* ET = PT->getElementType();
596 bool isForward = printTypeInternal(ET);
597 std::string elemName(getCppName(ET));
598 Out << "VectorType* " << typeName << " = VectorType::get("
599 << elemName << (isForward ? "_fwd" : "")
600 << ", " << utostr(PT->getNumElements()) << ");";
601 nl(Out);
602 break;
603 }
604 case Type::OpaqueTyID: {
605 Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
606 nl(Out);
607 break;
608 }
609 default:
610 error("Invalid TypeID");
611 }
612
613 // If the type had a name, make sure we recreate it.
614 const std::string* progTypeName =
615 findTypeName(TheModule->getTypeSymbolTable(),Ty);
616 if (progTypeName) {
617 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
618 << typeName << ");";
619 nl(Out);
620 }
621
622 // Pop us off the type stack
623 TypeStack.pop_back();
624
625 // Indicate that this type is now defined.
626 DefinedTypes.insert(Ty);
627
628 // Early resolve as many unresolved types as possible. Search the unresolved
629 // types map for the type we just printed. Now that its definition is complete
630 // we can resolve any previous references to it. This prevents a cascade of
631 // unresolved types.
632 TypeMap::iterator I = UnresolvedTypes.find(Ty);
633 if (I != UnresolvedTypes.end()) {
634 Out << "cast(" << I->second
635 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
636 nl(Out);
637 Out << I->second << " = cast<";
638 switch (Ty->getTypeID()) {
639 case Type::FunctionTyID: Out << "FunctionType"; break;
640 case Type::ArrayTyID: Out << "ArrayType"; break;
641 case Type::StructTyID: Out << "StructType"; break;
642 case Type::VectorTyID: Out << "VectorType"; break;
643 case Type::PointerTyID: Out << "PointerType"; break;
644 case Type::OpaqueTyID: Out << "OpaqueType"; break;
645 default: Out << "NoSuchDerivedType"; break;
646 }
647 Out << ">(" << I->second << "_fwd.get());";
648 nl(Out); nl(Out);
649 UnresolvedTypes.erase(I);
650 }
651
652 // Finally, separate the type definition from other with a newline.
653 nl(Out);
654
655 // We weren't a recursive type
656 return false;
657 }
658
659 // Prints a type definition. Returns true if it could not resolve all the types
660 // in the definition but had to use a forward reference.
661 void
662 CppWriter::printType(const Type* Ty) {
663 assert(TypeStack.empty());
664 TypeStack.clear();
665 printTypeInternal(Ty);
666 assert(TypeStack.empty());
667 }
668
669 void
670 CppWriter::printTypes(const Module* M) {
671
672 // Walk the symbol table and print out all its types
673 const TypeSymbolTable& symtab = M->getTypeSymbolTable();
674 for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
675 TI != TE; ++TI) {
676
677 // For primitive types and types already defined, just add a name
678 TypeMap::const_iterator TNI = TypeNames.find(TI->second);
679 if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
680 TNI != TypeNames.end()) {
681 Out << "mod->addTypeName(\"";
682 printEscapedString(TI->first);
683 Out << "\", " << getCppName(TI->second) << ");";
684 nl(Out);
685 // For everything else, define the type
686 } else {
687 printType(TI->second);
688 }
689 }
690
691 // Add all of the global variables to the value table...
692 for (Module::const_global_iterator I = TheModule->global_begin(),
693 E = TheModule->global_end(); I != E; ++I) {
694 if (I->hasInitializer())
695 printType(I->getInitializer()->getType());
696 printType(I->getType());
697 }
698
699 // Add all the functions to the table
700 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
701 FI != FE; ++FI) {
702 printType(FI->getReturnType());
703 printType(FI->getFunctionType());
704 // Add all the function arguments
705 for(Function::const_arg_iterator AI = FI->arg_begin(),
706 AE = FI->arg_end(); AI != AE; ++AI) {
707 printType(AI->getType());
708 }
709
710 // Add all of the basic blocks and instructions
711 for (Function::const_iterator BB = FI->begin(),
712 E = FI->end(); BB != E; ++BB) {
713 printType(BB->getType());
714 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
715 ++I) {
716 printType(I->getType());
717 for (unsigned i = 0; i < I->getNumOperands(); ++i)
718 printType(I->getOperand(i)->getType());
719 }
720 }
721 }
722 }
723
724
725 // printConstant - Print out a constant pool entry...
726 void CppWriter::printConstant(const Constant *CV) {
727 // First, if the constant is actually a GlobalValue (variable or function) or
728 // its already in the constant list then we've printed it already and we can
729 // just return.
730 if (isa(CV) || ValueNames.find(CV) != ValueNames.end())
731 return;
732
733 std::string constName(getCppName(CV));
734 std::string typeName(getCppName(CV->getType()));
735 if (CV->isNullValue()) {
736 Out << "Constant* " << constName << " = Constant::getNullValue("
737 << typeName << ");";
738 nl(Out);
739 return;
740 }
741 if (isa(CV)) {
742 // Skip variables and functions, we emit them elsewhere
743 return;
744 }
745 if (const ConstantInt *CI = dyn_cast(CV)) {
746 Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
747 << cast(CI->getType())->getBitWidth() << ", "
748 << " \"" << CI->getValue().toStringSigned(10) << "\", 10));";
749 } else if (isa(CV)) {
750 Out << "ConstantAggregateZero* " << constName
751 << " = ConstantAggregateZero::get(" << typeName << ");";
752 } else if (isa(CV)) {
753 Out << "ConstantPointerNull* " << constName
754 << " = ConstanPointerNull::get(" << typeName << ");";
755 } else if (const ConstantFP *CFP = dyn_cast(CV)) {
756 Out << "ConstantFP* " << constName << " = ";
757 printCFP(CFP);
758 Out << ";";
759 } else if (const ConstantArray *CA = dyn_cast(CV)) {
760 if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
761 Out << "Constant* " << constName << " = ConstantArray::get(\"";
762 std::string tmp = CA->getAsString();
763 bool nullTerminate = false;
764 if (tmp[tmp.length()-1] == 0) {
765 tmp.erase(tmp.length()-1);
766 nullTerminate = true;
767 }
768 printEscapedString(tmp);
769 // Determine if we want null termination or not.
770 if (nullTerminate)
771 Out << "\", true"; // Indicate that the null terminator should be added.
772 else
773 Out << "\", false";// No null terminator
774 Out << ");";
775 } else {
776 Out << "std::vector " << constName << "_elems;";
777 nl(Out);
778 unsigned N = CA->getNumOperands();
779 for (unsigned i = 0; i < N; ++i) {
780 printConstant(CA->getOperand(i)); // recurse to print operands
781 Out << constName << "_elems.push_back("
782 << getCppName(CA->getOperand(i)) << ");";
783 nl(Out);
784 }
785 Out << "Constant* " << constName << " = ConstantArray::get("
786 << typeName << ", " << constName << "_elems);";
787 }
788 } else if (const ConstantStruct *CS = dyn_cast(CV)) {
789 Out << "std::vector " << constName << "_fields;";
790 nl(Out);
791 unsigned N = CS->getNumOperands();
792 for (unsigned i = 0; i < N; i++) {
793 printConstant(CS->getOperand(i));
794 Out << constName << "_fields.push_back("
795 << getCppName(CS->getOperand(i)) << ");";
796 nl(Out);
797 }
798 Out << "Constant* " << constName << " = ConstantStruct::get("
799 << typeName << ", " << constName << "_fields);";
800 } else if (const ConstantVector *CP = dyn_cast(CV)) {
801 Out << "std::vector " << constName << "_elems;";
802 nl(Out);
803 unsigned N = CP->getNumOperands();
804 for (unsigned i = 0; i < N; ++i) {
805 printConstant(CP->getOperand(i));
806 Out << constName << "_elems.push_back("
807 << getCppName(CP->getOperand(i)) << ");";
808 nl(Out);
809 }
810 Out << "Constant* " << constName << " = ConstantVector::get("
811 << typeName << ", " << constName << "_elems);";
812 } else if (isa(CV)) {
813 Out << "UndefValue* " << constName << " = UndefValue::get("
814 << typeName << ");";
815 } else if (const ConstantExpr *CE = dyn_cast(CV)) {
816 if (CE->getOpcode() == Instruction::GetElementPtr) {
817 Out << "std::vector " << constName << "_indices;";
818 nl(Out);
819 printConstant(CE->getOperand(0));
820 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
821 printConstant(CE->getOperand(i));
822 Out << constName << "_indices.push_back("
823 << getCppName(CE->getOperand(i)) << ");";
824 nl(Out);
825 }
826 Out << "Constant* " << constName
827 << " = ConstantExpr::getGetElementPtr("
828 << getCppName(CE->getOperand(0)) << ", "
829 << "&" << constName << "_indices[0], "
830 << constName << "_indices.size()"
831 << " );";
832 } else if (CE->isCast()) {
833 printConstant(CE->getOperand(0));
834 Out << "Constant* " << constName << " = ConstantExpr::getCast(";
835 switch (CE->getOpcode()) {
836 default: assert(0 && "Invalid cast opcode");
837 case Instruction::Trunc: Out << "Instruction::Trunc"; break;
838 case Instruction::ZExt: Out << "Instruction::ZExt"; break;
839 case Instruction::SExt: Out << "Instruction::SExt"; break;
840 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break;
841 case Instruction::FPExt: Out << "Instruction::FPExt"; break;
842 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break;
843 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break;
844 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break;
845 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break;
846 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break;
847 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break;
848 case Instruction::BitCast: Out << "Instruction::BitCast"; break;
849 }
850 Out << ", " << getCppName(CE->getOperand(0)) << ", "
851 << getCppName(CE->getType()) << ");";
852 } else {
853 unsigned N = CE->getNumOperands();
854 for (unsigned i = 0; i < N; ++i ) {
855 printConstant(CE->getOperand(i));
856 }
857 Out << "Constant* " << constName << " = ConstantExpr::";
858 switch (CE->getOpcode()) {
859 case Instruction::Add: Out << "getAdd("; break;
860 case Instruction::Sub: Out << "getSub("; break;
861 case Instruction::Mul: Out << "getMul("; break;
862 case Instruction::UDiv: Out << "getUDiv("; break;
863 case Instruction::SDiv: Out << "getSDiv("; break;
864 case Instruction::FDiv: Out << "getFDiv("; break;
865 case Instruction::URem: Out << "getURem("; break;
866 case Instruction::SRem: Out << "getSRem("; break;
867 case Instruction::FRem: Out << "getFRem("; break;
868 case Instruction::And: Out << "getAnd("; break;
869 case Instruction::Or: Out << "getOr("; break;
870 case Instruction::Xor: Out << "getXor("; break;
871 case Instruction::ICmp:
872 Out << "getICmp(ICmpInst::ICMP_";
873 switch (CE->getPredicate()) {
874 case ICmpInst::ICMP_EQ: Out << "EQ"; break;
875 case ICmpInst::ICMP_NE: Out << "NE"; break;
876 case ICmpInst::ICMP_SLT: Out << "SLT"; break;
877 case ICmpInst::ICMP_ULT: Out << "ULT"; break;
878 case ICmpInst::ICMP_SGT: Out << "SGT"; break;
879 case ICmpInst::ICMP_UGT: Out << "UGT"; break;
880 case ICmpInst::ICMP_SLE: Out << "SLE"; break;
881 case ICmpInst::ICMP_ULE: Out << "ULE"; break;
882 case ICmpInst::ICMP_SGE: Out << "SGE"; break;
883 case ICmpInst::ICMP_UGE: Out << "UGE"; break;
884 default: error("Invalid ICmp Predicate");
885 }
886 break;
887 case Instruction::FCmp:
888 Out << "getFCmp(FCmpInst::FCMP_";
889 switch (CE->getPredicate()) {
890 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
891 case FCmpInst::FCMP_ORD: Out << "ORD"; break;
892 case FCmpInst::FCMP_UNO: Out << "UNO"; break;
893 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break;
894 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break;
895 case FCmpInst::FCMP_ONE: Out << "ONE"; break;
896 case FCmpInst::FCMP_UNE: Out << "UNE"; break;
897 case FCmpInst::FCMP_OLT: Out << "OLT"; break;
898 case FCmpInst::FCMP_ULT: Out << "ULT"; break;
899 case FCmpInst::FCMP_OGT: Out << "OGT"; break;
900 case FCmpInst::FCMP_UGT: Out << "UGT"; break;
901 case FCmpInst::FCMP_OLE: Out << "OLE"; break;
902 case FCmpInst::FCMP_ULE: Out << "ULE"; break;
903 case FCmpInst::FCMP_OGE: Out << "OGE"; break;
904 case FCmpInst::FCMP_UGE: Out << "UGE"; break;
905 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break;
906 default: error("Invalid FCmp Predicate");
907 }
908 break;
909 case Instruction::Shl: Out << "getShl("; break;
910 case Instruction::LShr: Out << "getLShr("; break;
911 case Instruction::AShr: Out << "getAShr("; break;
912 case Instruction::Select: Out << "getSelect("; break;
913 case Instruction::ExtractElement: Out << "getExtractElement("; break;
914 case Instruction::InsertElement: Out << "getInsertElement("; break;
915 case Instruction::ShuffleVector: Out << "getShuffleVector("; break;
916 default:
917 error("Invalid constant expression");
918 break;
919 }
920 Out << getCppName(CE->getOperand(0));
921 for (unsigned i = 1; i < CE->getNumOperands(); ++i)
922 Out << ", " << getCppName(CE->getOperand(i));
923 Out << ");";
924 }
925 } else {
926 error("Bad Constant");
927 Out << "Constant* " << constName << " = 0; ";
928 }
929 nl(Out);
930 }
931
932 void
933 CppWriter::printConstants(const Module* M) {
934 // Traverse all the global variables looking for constant initializers
935 for (Module::const_global_iterator I = TheModule->global_begin(),
936 E = TheModule->global_end(); I != E; ++I)
937 if (I->hasInitializer())
938 printConstant(I->getInitializer());
939
940 // Traverse the LLVM functions looking for constants
941 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
942 FI != FE; ++FI) {
943 // Add all of the basic blocks and instructions
944 for (Function::const_iterator BB = FI->begin(),
945 E = FI->end(); BB != E; ++BB) {
946 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
947 ++I) {
948 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
949 if (Constant* C = dyn_cast(I->getOperand(i))) {
950 printConstant(C);
951 }
952 }
953 }
954 }
955 }
956 }
957
958 void CppWriter::printVariableUses(const GlobalVariable *GV) {
959 nl(Out) << "// Type Definitions";
960 nl(Out);
961 printType(GV->getType());
962 if (GV->hasInitializer()) {
963 Constant* Init = GV->getInitializer();
964 printType(Init->getType());
965 if (Function* F = dyn_cast(Init)) {
966 nl(Out)<< "/ Function Declarations"; nl(Out);
967 printFunctionHead(F);
968 } else if (GlobalVariable* gv = dyn_cast(Init)) {
969 nl(Out) << "// Global Variable Declarations"; nl(Out);
970 printVariableHead(gv);
971 } else {
972 nl(Out) << "// Constant Definitions"; nl(Out);
973 printConstant(gv);
974 }
975 if (GlobalVariable* gv = dyn_cast(Init)) {
976 nl(Out) << "// Global Variable Definitions"; nl(Out);
977 printVariableBody(gv);
978 }
979 }
980 }
981
982 void CppWriter::printVariableHead(const GlobalVariable *GV) {
983 nl(Out) << "GlobalVariable* " << getCppName(GV);
984 if (is_inline) {
985 Out << " = mod->getGlobalVariable(";
986 printEscapedString(GV->getName());
987 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
988 nl(Out) << "if (!" << getCppName(GV) << ") {";
989 in(); nl(Out) << getCppName(GV);
990 }
991 Out << " = new GlobalVariable(";
992 nl(Out) << "/*Type=*/";
993 printCppName(GV->getType()->getElementType());
994 Out << ",";
995 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
996 Out << ",";
997 nl(Out) << "/*Linkage=*/";
998 printLinkageType(GV->getLinkage());
999 Out << ",";
1000 nl(Out) << "/*Initializer=*/0, ";
1001 if (GV->hasInitializer()) {
1002 Out << "// has initializer, specified below";
1003 }
1004 nl(Out) << "/*Name=*/\"";
1005 printEscapedString(GV->getName());
1006 Out << "\",";
1007 nl(Out) << "mod);";
1008 nl(Out);
1009
1010 if (GV->hasSection()) {
1011 printCppName(GV);
1012 Out << "->setSection(\"";
1013 printEscapedString(GV->getSection());
1014 Out << "\");";
1015 nl(Out);
1016 }
1017 if (GV->getAlignment()) {
1018 printCppName(GV);
1019 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1020 nl(Out);
1021 };
1022 if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1023 printCppName(GV);
1024 Out << "->setVisibility(";
1025 printVisibilityType(GV->getVisibility());
1026 Out << ");";
1027 nl(Out);
1028 }
1029 if (is_inline) {
1030 out(); Out << "}"; nl(Out);
1031 }
1032 }
1033
1034 void
1035 CppWriter::printVariableBody(const GlobalVariable *GV) {
1036 if (GV->hasInitializer()) {
1037 printCppName(GV);
1038 Out << "->setInitializer(";
1039 //if (!isagetInitializer()))
1040 //else
1041 Out << getCppName(GV->getInitializer()) << ");";
1042 nl(Out);
1043 }
1044 }
1045
1046 std::string
1047 CppWriter::getOpName(Value* V) {
1048 if (!isa(V) || DefinedValues.find(V) != DefinedValues.end())
1049 return getCppName(V);
1050
1051 // See if its alread in the map of forward references, if so just return the
1052 // name we already set up for it
1053 ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1054 if (I != ForwardRefs.end())
1055 return I->second;
1056
1057 // This is a new forward reference. Generate a unique name for it
1058 std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1059
1060 // Yes, this is a hack. An Argument is the smallest instantiable value that
1061 // we can make as a placeholder for the real value. We'll replace these
1062 // Argument instances later.
1063 Out << "Argument* " << result << " = new Argument("
1064 << getCppName(V->getType()) << ");";
1065 nl(Out);
1066 ForwardRefs[V] = result;
1067 return result;
1068 }
1069
1070 // printInstruction - This member is called for each Instruction in a function.
1071 void
1072 CppWriter::printInstruction(const Instruction *I, const std::string& bbname) {
1073 std::string iName(getCppName(I));
1074
1075 // Before we emit this instruction, we need to take care of generating any
1076 // forward references. So, we get the names of all the operands in advance
1077 std::string* opNames = new std::string[I->getNumOperands()];
1078 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1079 opNames[i] = getOpName(I->getOperand(i));
1080 }
1081
1082 switch (I->getOpcode()) {
1083 case Instruction::Ret: {
1084 const ReturnInst* ret = cast(I);
1085 Out << "ReturnInst::Create("
1086 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1087 break;
1088 }
1089 case Instruction::Br: {
1090 const BranchInst* br = cast(I);
1091 Out << "BranchInst::Create(" ;
1092 if (br->getNumOperands() == 3 ) {
1093 Out << opNames[0] << ", "
1094 << opNames[1] << ", "
1095 << opNames[2] << ", ";
1096
1097 } else if (br->getNumOperands() == 1) {
1098 Out << opNames[0] << ", ";
1099 } else {
1100 error("Branch with 2 operands?");
1101 }
1102 Out << bbname << ");";
1103 break;
1104 }
1105 case Instruction::Switch: {
1106 const SwitchInst* sw = cast(I);
1107 Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1108 << opNames[0] << ", "
1109 << opNames[1] << ", "
1110 << sw->getNumCases() << ", " << bbname << ");";
1111 nl(Out);
1112 for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1113 Out << iName << "->addCase("
1114 << opNames[i] << ", "
1115 << opNames[i+1] << ");";
1116 nl(Out);
1117 }
1118 break;
1119 }
1120 case Instruction::Invoke: {
1121 const InvokeInst* inv = cast(I);
1122 Out << "std::vector " << iName << "_params;";
1123 nl(Out);
1124 for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1125 Out << iName << "_params.push_back("
1126 << opNames[i] << ");";
1127 nl(Out);
1128 }
1129 Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1130 << opNames[0] << ", "
1131 << opNames[1] << ", "
1132 << opNames[2] << ", "
1133 << iName << "_params.begin(), " << iName << "_params.end(), \"";
1134 printEscapedString(inv->getName());
1135 Out << "\", " << bbname << ");";
1136 nl(Out) << iName << "->setCallingConv(";
1137 printCallingConv(inv->getCallingConv());
1138 Out << ");";
1139 printParamAttrs(inv->getParamAttrs(), iName);
1140 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1141 nl(Out);
1142 break;
1143 }
1144 case Instruction::Unwind: {
1145 Out << "new UnwindInst("
1146 << bbname << ");";
1147 break;
1148 }
1149 case Instruction::Unreachable:{
1150 Out << "new UnreachableInst("
1151 << bbname << ");";
1152 break;
1153 }
1154 case Instruction::Add:
1155 case Instruction::Sub:
1156 case Instruction::Mul:
1157 case Instruction::UDiv:
1158 case Instruction::SDiv:
1159 case Instruction::FDiv:
1160 case Instruction::URem:
1161 case Instruction::SRem:
1162 case Instruction::FRem:
1163 case Instruction::And:
1164 case Instruction::Or:
1165 case Instruction::Xor:
1166 case Instruction::Shl:
1167 case Instruction::LShr:
1168 case Instruction::AShr:{
1169 Out << "BinaryOperator* " << iName << " = BinaryOperator::create(";
1170 switch (I->getOpcode()) {
1171 case Instruction::Add: Out << "Instruction::Add"; break;
1172 case Instruction::Sub: Out << "Instruction::Sub"; break;
1173 case Instruction::Mul: Out << "Instruction::Mul"; break;
1174 case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1175 case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1176 case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1177 case Instruction::URem:Out << "Instruction::URem"; break;
1178 case Instruction::SRem:Out << "Instruction::SRem"; break;
1179 case Instruction::FRem:Out << "Instruction::FRem"; break;
1180 case Instruction::And: Out << "Instruction::And"; break;
1181 case Instruction::Or: Out << "Instruction::Or"; break;
1182 case Instruction::Xor: Out << "Instruction::Xor"; break;
1183 case Instruction::Shl: Out << "Instruction::Shl"; break;
1184 case Instruction::LShr:Out << "Instruction::LShr"; break;
1185 case Instruction::AShr:Out << "Instruction::AShr"; break;
1186 default: Out << "Instruction::BadOpCode"; break;
1187 }
1188 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1189 printEscapedString(I->getName());
1190 Out << "\", " << bbname << ");";
1191 break;
1192 }
1193 case Instruction::FCmp: {
1194 Out << "FCmpInst* " << iName << " = new FCmpInst(";
1195 switch (cast(I)->getPredicate()) {
1196 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1197 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break;
1198 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break;
1199 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break;
1200 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break;
1201 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break;
1202 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break;
1203 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break;
1204 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break;
1205 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break;
1206 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break;
1207 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break;
1208 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break;
1209 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break;
1210 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break;
1211 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1212 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1213 }
1214 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1215 printEscapedString(I->getName());
1216 Out << "\", " << bbname << ");";
1217 break;
1218 }
1219 case Instruction::ICmp: {
1220 Out << "ICmpInst* " << iName << " = new ICmpInst(";
1221 switch (cast(I)->getPredicate()) {
1222 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break;
1223 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break;
1224 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1225 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1226 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1227 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1228 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1229 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1230 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1231 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1232 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1233 }
1234 Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1235 printEscapedString(I->getName());
1236 Out << "\", " << bbname << ");";
1237 break;
1238 }
1239 case Instruction::Malloc: {
1240 const MallocInst* mallocI = cast(I);
1241 Out << "MallocInst* " << iName << " = new MallocInst("
1242 << getCppName(mallocI->getAllocatedType()) << ", ";
1243 if (mallocI->isArrayAllocation())
1244 Out << opNames[0] << ", " ;
1245 Out << "\"";
1246 printEscapedString(mallocI->getName());
1247 Out << "\", " << bbname << ");";
1248 if (mallocI->getAlignment())
1249 nl(Out) << iName << "->setAlignment("
1250 << mallocI->getAlignment() << ");";
1251 break;
1252 }
1253 case Instruction::Free: {
1254 Out << "FreeInst* " << iName << " = new FreeInst("
1255 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1256 break;
1257 }
1258 case Instruction::Alloca: {
1259 const AllocaInst* allocaI = cast(I);
1260 Out << "AllocaInst* " << iName << " = new AllocaInst("
1261 << getCppName(allocaI->getAllocatedType()) << ", ";
1262 if (allocaI->isArrayAllocation())
1263 Out << opNames[0] << ", ";
1264 Out << "\"";
1265 printEscapedString(allocaI->getName());
1266 Out << "\", " << bbname << ");";
1267 if (allocaI->getAlignment())
1268 nl(Out) << iName << "->setAlignment("
1269 << allocaI->getAlignment() << ");";
1270 break;
1271 }
1272 case Instruction::Load:{
1273 const LoadInst* load = cast(I);
1274 Out << "LoadInst* " << iName << " = new LoadInst("
1275 << opNames[0] << ", \"";
1276 printEscapedString(load->getName());
1277 Out << "\", " << (load->isVolatile() ? "true" : "false" )
1278 << ", " << bbname << ");";
1279 break;
1280 }
1281 case Instruction::Store: {
1282 const StoreInst* store = cast(I);
1283 Out << "StoreInst* " << iName << " = new StoreInst("
1284 << opNames[0] << ", "
1285 << opNames[1] << ", "
1286 << (store->isVolatile() ? "true" : "false")
1287 << ", " << bbname << ");";
1288 break;
1289 }
1290 case Instruction::GetElementPtr: {
1291 const GetElementPtrInst* gep = cast(I);
1292 if (gep->getNumOperands() <= 2) {
1293 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1294 << opNames[0];
1295 if (gep->getNumOperands() == 2)
1296 Out << ", " << opNames[1];
1297 } else {
1298 Out << "std::vector " << iName << "_indices;";
1299 nl(Out);
1300 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1301 Out << iName << "_indices.push_back("
1302 << opNames[i] << ");";
1303 nl(Out);
1304 }
1305 Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1306 << opNames[0] << ", " << iName << "_indices.begin(), "
1307 << iName << "_indices.end()";
1308 }
1309 Out << ", \"";
1310 printEscapedString(gep->getName());
1311 Out << "\", " << bbname << ");";
1312 break;
1313 }
1314 case Instruction::PHI: {
1315 const PHINode* phi = cast(I);
1316
1317 Out << "PHINode* " << iName << " = PHINode::Create("
1318 << getCppName(phi->getType()) << ", \"";
1319 printEscapedString(phi->getName());
1320 Out << "\", " << bbname << ");";
1321 nl(Out) << iName << "->reserveOperandSpace("
1322 << phi->getNumIncomingValues()
1323 << ");";
1324 nl(Out);
1325 for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1326 Out << iName << "->addIncoming("
1327 << opNames[i] << ", " << opNames[i+1] << ");";
1328 nl(Out);
1329 }
1330 break;
1331 }
1332 case Instruction::Trunc:
1333 case Instruction::ZExt:
1334 case Instruction::SExt:
1335 case Instruction::FPTrunc:
1336 case Instruction::FPExt:
1337 case Instruction::FPToUI:
1338 case Instruction::FPToSI:
1339 case Instruction::UIToFP:
1340 case Instruction::SIToFP:
1341 case Instruction::PtrToInt:
1342 case Instruction::IntToPtr:
1343 case Instruction::BitCast: {
1344 const CastInst* cst = cast(I);
1345 Out << "CastInst* " << iName << " = new ";
1346 switch (I->getOpcode()) {
1347 case Instruction::Trunc: Out << "TruncInst"; break;
1348 case Instruction::ZExt: Out << "ZExtInst"; break;
1349 case Instruction::SExt: Out << "SExtInst"; break;
1350 case Instruction::FPTrunc: Out << "FPTruncInst"; break;
1351 case Instruction::FPExt: Out << "FPExtInst"; break;
1352 case Instruction::FPToUI: Out << "FPToUIInst"; break;
1353 case Instruction::FPToSI: Out << "FPToSIInst"; break;
1354 case Instruction::UIToFP: Out << "UIToFPInst"; break;
1355 case Instruction::SIToFP: Out << "SIToFPInst"; break;
1356 case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1357 case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1358 case Instruction::BitCast: Out << "BitCastInst"; break;
1359 default: assert(!"Unreachable"); break;
1360 }
1361 Out << "(" << opNames[0] << ", "
1362 << getCppName(cst->getType()) << ", \"";
1363 printEscapedString(cst->getName());
1364 Out << "\", " << bbname << ");";
1365 break;
1366 }
1367 case Instruction::Call:{
1368 const CallInst* call = cast(I);
1369 if (InlineAsm* ila = dyn_cast(call->getOperand(0))) {
1370 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1371 << getCppName(ila->getFunctionType()) << ", \""
1372 << ila->getAsmString() << "\", \""
1373 << ila->getConstraintString() << "\","
1374 << (ila->hasSideEffects() ? "true" : "false") << ");";
1375 nl(Out);
1376 }
1377 if (call->getNumOperands() > 2) {
1378 Out << "std::vector " << iName << "_params;";
1379 nl(Out);
1380 for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1381 Out << iName << "_params.push_back(" << opNames[i] << ");";
1382 nl(Out);
1383 }
1384 Out << "CallInst* " << iName << " = CallInst::Create("
1385 << opNames[0] << ", " << iName << "_params.begin(), "
1386 << iName << "_params.end(), \"";
1387 } else if (call->getNumOperands() == 2) {
1388 Out << "CallInst* " << iName << " = CallInst::Create("
1389 << opNames[0] << ", " << opNames[1] << ", \"";
1390 } else {
1391 Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1392 << ", \"";
1393 }
1394 printEscapedString(call->getName());
1395 Out << "\", " << bbname << ");";
1396 nl(Out) << iName << "->setCallingConv(";
1397 printCallingConv(call->getCallingConv());
1398 Out << ");";
1399 nl(Out) << iName << "->setTailCall("
1400 << (call->isTailCall() ? "true":"false");
1401 Out << ");";
1402 printParamAttrs(call->getParamAttrs(), iName);
1403 Out << iName << "->setParamAttrs(" << iName << "_PAL);";
1404 nl(Out);
1405 break;
1406 }
1407 case Instruction::Select: {
1408 const SelectInst* sel = cast(I);
1409 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1410 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1411 printEscapedString(sel->getName());
1412 Out << "\", " << bbname << ");";
1413 break;
1414 }
1415 case Instruction::UserOp1:
1416 /// FALL THROUGH
1417 case Instruction::UserOp2: {
1418 /// FIXME: What should be done here?
1419 break;
1420 }
1421 case Instruction::VAArg: {
1422 const VAArgInst* va = cast(I);
1423 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1424 << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1425 printEscapedString(va->getName());
1426 Out << "\", " << bbname << ");";
1427 break;
1428 }
1429 case Instruction::ExtractElement: {
1430 const ExtractElementInst* eei = cast(I);
1431 Out << "ExtractElementInst* " << getCppName(eei)
1432 << " = new ExtractElementInst(" << opNames[0]
1433 << ", " << opNames[1] << ", \"";
1434 printEscapedString(eei->getName());
1435 Out << "\", " << bbname << ");";
1436 break;
1437 }
1438 case Instruction::InsertElement: {
1439 const InsertElementInst* iei = cast(I);
1440 Out << "InsertElementInst* " << getCppName(iei)
1441 << " = InsertElementInst::Create(" << opNames[0]
1442 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1443 printEscapedString(iei->getName());
1444 Out << "\", " << bbname << ");";
1445 break;
1446 }
1447 case Instruction::ShuffleVector: {
1448 const ShuffleVectorInst* svi = cast(I);
1449 Out << "ShuffleVectorInst* " << getCppName(svi)
1450 << " = new ShuffleVectorInst(" << opNames[0]
1451 << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1452 printEscapedString(svi->getName());
1453 Out << "\", " << bbname << ");";
1454 break;
1455 }
1456 }
1457 DefinedValues.insert(I);
1458 nl(Out);
1459 delete [] opNames;
1460 }
1461
1462 // Print out the types, constants and declarations needed by one function
1463 void CppWriter::printFunctionUses(const Function* F) {
1464
1465 nl(Out) << "// Type Definitions"; nl(Out);
1466 if (!is_inline) {
1467 // Print the function's return type
1468 printType(F->getReturnType());
1469
1470 // Print the function's function type
1471 printType(F->getFunctionType());
1472
1473 // Print the types of each of the function's arguments
1474 for(Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1475 AI != AE; ++AI) {
1476 printType(AI->getType());
1477 }
1478 }
1479
1480 // Print type definitions for every type referenced by an instruction and
1481 // make a note of any global values or constants that are referenced
1482 SmallPtrSet gvs;
1483 SmallPtrSet consts;
1484 for (Function::const_iterator BB = F->begin(), BE = F->end(); BB != BE; ++BB){
1485 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1486 I != E; ++I) {
1487 // Print the type of the instruction itself
1488 printType(I->getType());
1489
1490 // Print the type of each of the instruction's operands
1491 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1492 Value* operand = I->getOperand(i);
1493 printType(operand->getType());
1494
1495 // If the operand references a GVal or Constant, make a note of it
1496 if (GlobalValue* GV = dyn_cast(operand)) {
1497 gvs.insert(GV);
1498 if (GlobalVariable *GVar = dyn_cast(GV))
1499 if (GVar->hasInitializer())
1500 consts.insert(GVar->getInitializer());
1501 } else if (Constant* C = dyn_cast(operand))
1502 consts.insert(C);
1503 }
1504 }
1505 }
1506
1507 // Print the function declarations for any functions encountered
1508 nl(Out) << "// Function Declarations"; nl(Out);
1509 for (SmallPtrSet::iterator I = gvs.begin(), E = gvs.end();
1510 I != E; ++I) {
1511 if (Function* Fun = dyn_cast(*I)) {
1512 if (!is_inline || Fun != F)
1513 printFunctionHead(Fun);
1514 }
1515 }
1516
1517 // Print the global variable declarations for any variables encountered
1518 nl(Out) << "// Global Variable Declarations"; nl(Out);
1519 for (SmallPtrSet::iterator I = gvs.begin(), E = gvs.end();
1520 I != E; ++I) {
1521 if (GlobalVariable* F = dyn_cast(*I))
1522 printVariableHead(F);
1523 }
1524
1525 // Print the constants found
1526 nl(Out) << "// Constant Definitions"; nl(Out);
1527 for (SmallPtrSet::iterator I = consts.begin(), E = consts.end();
1528 I != E; ++I) {
1529 printConstant(*I);
1530 }
1531
1532 // Process the global variables definitions now that all the constants have
1533 // been emitted. These definitions just couple the gvars with their constant
1534 // initializers.
1535 nl(Out) << "// Global Variable Definitions"; nl(Out);
1536 for (SmallPtrSet::iterator I = gvs.begin(), E = gvs.end();
1537 I != E; ++I) {
1538 if (GlobalVariable* GV = dyn_cast(*I))
1539 printVariableBody(GV);
1540 }
1541 }
1542
1543 void CppWriter::printFunctionHead(const Function* F) {
1544 nl(Out) << "Function* " << getCppName(F);
1545 if (is_inline) {
1546 Out << " = mod->getFunction(\"";
1547 printEscapedString(F->getName());
1548 Out << "\", " << getCppName(F->getFunctionType()) << ");";
1549 nl(Out) << "if (!" << getCppName(F) << ") {";
1550 nl(Out) << getCppName(F);
1551 }
1552 Out<< " = Function::Create(";
1553 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1554 nl(Out) << "/*Linkage=*/";
1555 printLinkageType(F->getLinkage());
1556 Out << ",";
1557 nl(Out) << "/*Name=*/\"";
1558 printEscapedString(F->getName());
1559 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1560 nl(Out,-1);
1561 printCppName(F);
1562 Out << "->setCallingConv(";
1563 printCallingConv(F->getCallingConv());
1564 Out << ");";
1565 nl(Out);
1566 if (F->hasSection()) {
1567 printCppName(F);
1568 Out << "->setSection(\"" << F->getSection() << "\");";
1569 nl(Out);
1570 }
1571 if (F->getAlignment()) {
1572 printCppName(F);
1573 Out << "->setAlignment(" << F->getAlignment() << ");";
1574 nl(Out);
1575 }
1576 if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1577 printCppName(F);
1578 Out << "->setVisibility(";
1579 printVisibilityType(F->getVisibility());
1580 Out << ");";
1581 nl(Out);
1582 }
1583 if (F->hasCollector()) {
1584 printCppName(F);
1585 Out << "->setCollector(\"" << F->getCollector() << "\");";
1586 nl(Out);
1587 }
1588 if (is_inline) {
1589 Out << "}";
1590 nl(Out);
1591 }
1592 printParamAttrs(F->getParamAttrs(), getCppName(F));
1593 printCppName(F);
1594 Out << "->setParamAttrs(" << getCppName(F) << "_PAL);";
1595 nl(Out);
1596 }
1597
1598 void CppWriter::printFunctionBody(const Function *F) {
1599 if (F->isDeclaration())
1600 return; // external functions have no bodies.
1601
1602 // Clear the DefinedValues and ForwardRefs maps because we can't have
1603 // cross-function forward refs
1604 ForwardRefs.clear();
1605 DefinedValues.clear();
1606
1607 // Create all the argument values
1608 if (!is_inline) {
1609 if (!F->arg_empty()) {
1610 Out << "Function::arg_iterator args = " << getCppName(F)
1611 << "->arg_begin();";
1612 nl(Out);
1613 }
1614 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1615 AI != AE; ++AI) {
1616 Out << "Value* " << getCppName(AI) << " = args++;";
1617 nl(Out);
1618 if (AI->hasName()) {
1619 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1620 nl(Out);
1621 }
1622 }
1623 }
1624
1625 // Create all the basic blocks
1626 nl(Out);
1627 for (Function::const_iterator BI = F->begin(), BE = F->end();
1628 BI != BE; ++BI) {
1629 std::string bbname(getCppName(BI));
1630 Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1631 if (BI->hasName())
1632 printEscapedString(BI->getName());
1633 Out << "\"," << getCppName(BI->getParent()) << ",0);";
1634 nl(Out);
1635 }
1636
1637 // Output all of its basic blocks... for the function
1638 for (Function::const_iterator BI = F->begin(), BE = F->end();
1639 BI != BE; ++BI) {
1640 std::string bbname(getCppName(BI));
1641 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1642 nl(Out);
1643
1644 // Output all of the instructions in the basic block...
1645 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1646 I != E; ++I) {
1647 printInstruction(I,bbname);
1648 }
1649 }
1650
1651 // Loop over the ForwardRefs and resolve them now that all instructions
1652 // are generated.
1653 if (!ForwardRefs.empty()) {
1654 nl(Out) << "// Resolve Forward References";
1655 nl(Out);
1656 }
1657
1658 while (!ForwardRefs.empty()) {
1659 ForwardRefMap::iterator I = ForwardRefs.begin();
1660 Out << I->second << "->replaceAllUsesWith("
1661 << getCppName(I->first) << "); delete " << I->second << ";";
1662 nl(Out);
1663 ForwardRefs.erase(I);
1664 }
1665 }
1666
1667 void CppWriter::printInline(const std::string& fname, const std::string& func) {
1668 const Function* F = TheModule->getFunction(func);
1669 if (!F) {
1670 error(std::string("Function '") + func + "' not found in input module");
1671 return;
1672 }
1673 if (F->isDeclaration()) {
1674 error(std::string("Function '") + func + "' is external!");
1675 return;
1676 }
1677 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1678 << getCppName(F);
1679 unsigned arg_count = 1;
1680 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1681 AI != AE; ++AI) {
1682 Out << ", Value* arg_" << arg_count;
1683 }
1684 Out << ") {";
1685 nl(Out);
1686 is_inline = true;
1687 printFunctionUses(F);
1688 printFunctionBody(F);
1689 is_inline = false;
1690 Out << "return " << getCppName(F->begin()) << ";";
1691 nl(Out) << "}";
1692 nl(Out);
1693 }
1694
1695 void CppWriter::printModuleBody() {
1696 // Print out all the type definitions
1697 nl(Out) << "// Type Definitions"; nl(Out);
1698 printTypes(TheModule);
1699
1700 // Functions can call each other and global variables can reference them so
1701 // define all the functions first before emitting their function bodies.
1702 nl(Out) << "// Function Declarations"; nl(Out);
1703 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1704 I != E; ++I)
1705 printFunctionHead(I);
1706
1707 // Process the global variables declarations. We can't initialze them until
1708 // after the constants are printed so just print a header for each global
1709 nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1710 for (Module::const_global_iterator I = TheModule->global_begin(),
1711 E = TheModule->global_end(); I != E; ++I) {
1712 printVariableHead(I);
1713 }
1714
1715 // Print out all the constants definitions. Constants don't recurse except
1716 // through GlobalValues. All GlobalValues have been declared at this point
1717 // so we can proceed to generate the constants.
1718 nl(Out) << "// Constant Definitions"; nl(Out);
1719 printConstants(TheModule);
1720
1721 // Process the global variables definitions now that all the constants have
1722 // been emitted. These definitions just couple the gvars with their constant
1723 // initializers.
1724 nl(Out) << "// Global Variable Definitions"; nl(Out);
1725 for (Module::const_global_iterator I = TheModule->global_begin(),
1726 E = TheModule->global_end(); I != E; ++I) {
1727 printVariableBody(I);
1728 }
1729
1730 // Finally, we can safely put out all of the function bodies.
1731 nl(Out) << "// Function Definitions"; nl(Out);
1732 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1733 I != E; ++I) {
1734 if (!I->isDeclaration()) {
1735 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1736 << ")";
1737 nl(Out) << "{";
1738 nl(Out,1);
1739 printFunctionBody(I);
1740 nl(Out,-1) << "}";
1741 nl(Out);
1742 }
1743 }
1744 }
1745
1746 void CppWriter::printProgram(
1747 const std::string& fname,
1748 const std::string& mName
1749 ) {
1750 Out << "#include \n";
1751 Out << "#include \n";
1752 Out << "#include \n";
1753 Out << "#include \n";
1754 Out << "#include \n";
1755 Out << "#include \n";
1756 Out << "#include \n";
1757 Out << "#include \n";
1758 Out << "#include \n";
1759 Out << "#include \n";
1760 Out << "#include \n";
1761 Out << "#include \n";
1762 Out << "#include \n";
1763 Out << "#include \n";
1764 Out << "#include \n";
1765 Out << "#include \n\n";
1766 Out << "using namespace llvm;\n\n";
1767 Out << "Module* " << fname << "();\n\n";
1768 Out << "int main(int argc, char**argv) {\n";
1769 Out << " Module* Mod = " << fname << "();\n";
1770 Out << " verifyModule(*Mod, PrintMessageAction);\n";
1771 Out << " std::cerr.flush();\n";
1772 Out << " std::cout.flush();\n";
1773 Out << " PassManager PM;\n";
1774 Out << " PM.add(new PrintModulePass(&llvm::cout));\n";
1775 Out << " PM.run(*Mod);\n";
1776 Out << " return 0;\n";
1777 Out << "}\n\n";
1778 printModule(fname,mName);
1779 }
1780
1781 void CppWriter::printModule(
1782 const std::string& fname,
1783 const std::string& mName
1784 ) {
1785 nl(Out) << "Module* " << fname << "() {";
1786 nl(Out,1) << "// Module Construction";
1787 nl(Out) << "Module* mod = new Module(\"" << mName << "\");";
1788 if (!TheModule->getTargetTriple().empty()) {
1789 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1790 }
1791 if (!TheModule->getTargetTriple().empty()) {
1792 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1793 << "\");";
1794 }
1795
1796 if (!TheModule->getModuleInlineAsm().empty()) {
1797 nl(Out) << "mod->setModuleInlineAsm(\"";
1798 printEscapedString(TheModule->getModuleInlineAsm());
1799 Out << "\");";
1800 }
1801 nl(Out);
1802
1803 // Loop over the dependent libraries and emit them.
1804 Module::lib_iterator LI = TheModule->lib_begin();
1805 Module::lib_iterator LE = TheModule->lib_end();
1806 while (LI != LE) {
1807 Out << "mod->addLibrary(\"" << *LI << "\");";
1808 nl(Out);
1809 ++LI;
1810 }
1811 printModuleBody();
1812 nl(Out) << "return mod;";
1813 nl(Out,-1) << "}";
1814 nl(Out);
1815 }
1816
1817 void CppWriter::printContents(
1818 const std::string& fname, // Name of generated function
1819 const std::string& mName // Name of module generated module
1820 ) {
1821 Out << "\nModule* " << fname << "(Module *mod) {\n";
1822 Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n";
1823 printModuleBody();
1824 Out << "\nreturn mod;\n";
1825 Out << "\n}\n";
1826 }
1827
1828 void CppWriter::printFunction(
1829 const std::string& fname, // Name of generated function
1830 const std::string& funcName // Name of function to generate
1831 ) {
1832 const Function* F = TheModule->getFunction(funcName);
1833 if (!F) {
1834 error(std::string("Function '") + funcName + "' not found in input module");
1835 return;
1836 }
1837 Out << "\nFunction* " << fname << "(Module *mod) {\n";
1838 printFunctionUses(F);
1839 printFunctionHead(F);
1840 printFunctionBody(F);
1841 Out << "return " << getCppName(F) << ";\n";
1842 Out << "}\n";
1843 }
1844
1845 void CppWriter::printFunctions() {
1846 const Module::FunctionListType &funcs = TheModule->getFunctionList();
1847 Module::const_iterator I = funcs.begin();
1848 Module::const_iterator IE = funcs.end();
1849
1850 for (; I != IE; ++I) {
1851 const Function &func = *I;
1852 if (!func.isDeclaration()) {
1853 std::string name("define_");
1854 name += func.getName();
1855 printFunction(name, func.getName());
1856 }
1857 }
1858 }
1859
1860 void CppWriter::printVariable(
1861 const std::string& fname, /// Name of generated function
1862 const std::string& varName // Name of variable to generate
1863 ) {
1864 const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1865
1866 if (!GV) {
1867 error(std::string("Variable '") + varName + "' not found in input module");
1868 return;
1869 }
1870 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1871 printVariableUses(GV);
1872 printVariableHead(GV);
1873 printVariableBody(GV);
1874 Out << "return " << getCppName(GV) << ";\n";
1875 Out << "}\n";
1876 }
1877
1878 void CppWriter::printType(
1879 const std::string& fname, /// Name of generated function
1880 const std::string& typeName // Name of type to generate
1881 ) {
1882 const Type* Ty = TheModule->getTypeByName(typeName);
1883 if (!Ty) {
1884 error(std::string("Type '") + typeName + "' not found in input module");
1885 return;
1886 }
1887 Out << "\nType* " << fname << "(Module *mod) {\n";
1888 printType(Ty);
1889 Out << "return " << getCppName(Ty) << ";\n";
1890 Out << "}\n";
1891 }
1892
1893 } // end anonymous llvm
1894
1895 namespace llvm {
1896
1897 void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1898 // Initialize a CppWriter for us to use
1899 CppWriter W(o, mod);
1900
1901 // Emit a header
1902 o << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1903
1904 // Get the name of the function we're supposed to generate
1905 std::string fname = FuncName.getValue();
1906
1907 // Get the name of the thing we are to generate
1908 std::string tgtname = NameToGenerate.getValue();
1909 if (GenerationType == GenModule ||
1910 GenerationType == GenContents ||
1911 GenerationType == GenProgram ||
1912 GenerationType == GenFunctions) {
1913 if (tgtname == "!bad!") {
1914 if (mod->getModuleIdentifier() == "-")
1915 tgtname = "";
1916 else
1917 tgtname = mod->getModuleIdentifier();
1918 }
1919 } else if (tgtname == "!bad!") {
1920 W.error("You must use the -for option with -gen-{function,variable,type}");
1921 }
1922
1923 switch (WhatToGenerate(GenerationType)) {
1924 case GenProgram:
1925 if (fname.empty())
1926 fname = "makeLLVMModule";
1927 W.printProgram(fname,tgtname);
1928 break;
1929 case GenModule:
1930 if (fname.empty())
1931 fname = "makeLLVMModule";
1932 W.printModule(fname,tgtname);
1933 break;
1934 case GenContents:
1935 if (fname.empty())
1936 fname = "makeLLVMModuleContents";
1937 W.printContents(fname,tgtname);
1938 break;
1939 case GenFunction:
1940 if (fname.empty())
1941 fname = "makeLLVMFunction";
1942 W.printFunction(fname,tgtname);
1943 break;
1944 case GenFunctions:
1945 W.printFunctions();
1946 break;
1947 case GenInline:
1948 if (fname.empty())
1949 fname = "makeLLVMInline";
1950 W.printInline(fname,tgtname);
1951 break;
1952 case GenVariable:
1953 if (fname.empty())
1954 fname = "makeLLVMVariable";
1955 W.printVariable(fname,tgtname);
1956 break;
1957 case GenType:
1958 if (fname.empty())
1959 fname = "makeLLVMType";
1960 W.printType(fname,tgtname);
1961 break;
1962 default:
1963 W.error("Invalid generation option");
1964 }
1965 }
1966
1967 }
+0
-18
tools/llvm2cpp/CppWriter.h less more
None //===--- CppWriter.h - Generate C++ IR to C++ Source Interface ------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares a function, WriteModuleToCppFile that will convert a
10 // Module into the corresponding C++ code to construct the same module.
11 //
12 //===------------------------------------------------------------------------===
13 #include
14 namespace llvm {
15 class Module;
16 void WriteModuleToCppFile(Module* mod, std::ostream& out);
17 }
+0
-15
tools/llvm2cpp/Makefile less more
None ##===- tools/llvm2cpp/Makefile -----------------------------*- Makefile -*-===##
1 #
2 # The LLVM Compiler Infrastructure
3 #
4 # This file is distributed under the University of Illinois Open Source
5 # License. See LICENSE.TXT for details.
6 #
7 ##===----------------------------------------------------------------------===##
8 LEVEL = ../..
9 TOOLNAME = llvm2cpp
10 LINK_COMPONENTS = bitreader
11
12 include $(LEVEL)/Makefile.common
13
14 CompileCommonOpts := $(CompileCommonOpts) -Wno-format
+0
-122
tools/llvm2cpp/llvm2cpp.cpp less more
None //===--- llvm2cpp.cpp - LLVM IR to C++ Translator -------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This program converts an input LLVM assembly file (.ll) into a C++ source
10 // file that makes calls to the LLVM C++ API to produce the same module. The
11 // generated program verifies what it built and then runs the PrintAssemblyPass
12 // to reproduce the input originally given to llvm2cpp.
13 //
14 // Use the --help option for help with command line options.
15 //
16 //===------------------------------------------------------------------------===
17
18 #include "llvm/Module.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/Analysis/Verifier.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/SystemUtils.h"
25 #include "llvm/System/Signals.h"
26 #include "CppWriter.h"
27 #include
28 #include
29 #include
30 using namespace llvm;
31
32 static cl::opt
33 InputFilename(cl::Positional, cl::desc(""),
34 cl::init("-"));
35
36 static cl::opt
37 OutputFilename("o", cl::desc("Override output filename"),
38 cl::value_desc("filename"));
39
40 static cl::opt
41 Force("f", cl::desc("Overwrite output files"));
42
43 int main(int argc, char **argv) {
44 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
45 cl::ParseCommandLineOptions(argc, argv, "llvm .ll -> .cpp assembler\n");
46 sys::PrintStackTraceOnErrorSignal();
47
48 int exitCode = 0;
49 std::ostream *Out = 0;
50 std::string ErrorMessage;
51
52 std::auto_ptr M;
53 std::auto_ptr Buffer(
54 MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage));
55 if (Buffer.get())
56 M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage));
57 if (M.get() == 0) {
58 std::cerr << argv[0] << ": ";
59 if (ErrorMessage.size())
60 std::cerr << ErrorMessage << "\n";
61 else
62 std::cerr << "bitcode didn't read correctly.\n";
63 return 1;
64 }
65
66 if (OutputFilename != "") { // Specified an output filename?
67 if (OutputFilename != "-") { // Not stdout?
68 if (!Force && std::ifstream(OutputFilename.c_str())) {
69 // If force is not specified, make sure not to overwrite a file!
70 std::cerr << argv[0] << ": error opening '" << OutputFilename
71 << "': file exists!\n"
72 << "Use -f command line argument to force output\n";
73 return 1;
74 }
75 Out = new std::ofstream(OutputFilename.c_str(), std::ios::out |
76 std::ios::trunc | std::ios::binary);
77 } else { // Specified stdout
78 Out = &std::cout;
79 }
80 } else {
81 if (InputFilename == "-") {
82 OutputFilename = "-";
83 Out = &std::cout;
84 } else {
85 std::string IFN = InputFilename;
86 int Len = IFN.length();
87 if (IFN[Len-3] == '.' && IFN[Len-2] == 'l' && IFN[Len-1] == 'l') {
88 // Source ends in .ll
89 OutputFilename = std::string(IFN.begin(), IFN.end()-3);
90 } else {
91 OutputFilename = IFN; // Append a .cpp to it
92 }
93 OutputFilename += ".cpp";
94
95 if (!Force && std::ifstream(OutputFilename.c_str())) {
96 // If force is not specified, make sure not to overwrite a file!
97 std::cerr << argv[0] << ": error opening '" << OutputFilename
98 << "': file exists!\n"
99 << "Use -f command line argument to force output\n";
100 return 1;
101 }
102
103 Out = new std::ofstream(OutputFilename.c_str(), std::ios::out |
104 std::ios::trunc | std::ios::binary);
105 // Make sure that the Out file gets unlinked from the disk if we get a
106 // SIGINT
107 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
108 }
109 }
110
111 if (!Out->good()) {
112 std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
113 return 1;
114 }
115
116 WriteModuleToCppFile(M.get(), *Out);
117
118 if (Out != &std::cout) delete Out;
119 return exitCode;
120 }
121