blob: 0f28e30e16a1118e0f39ba49962544b199a1978c [file] [log] [blame]
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001//===-- CppWriter.cpp - Printing LLVM IR as a C++ Source File -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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 "llvm/CallingConv.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/InlineAsm.h"
19#include "llvm/Instruction.h"
20#include "llvm/Instructions.h"
21#include "llvm/Module.h"
22#include "llvm/SymbolTable.h"
23#include "llvm/Support/CFG.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/MathExtras.h"
27#include <algorithm>
28#include <iostream>
29
30using namespace llvm;
31
32namespace {
33/// This class provides computation of slot numbers for LLVM Assembly writing.
34/// @brief LLVM Assembly Writing Slot Computation.
35class SlotMachine {
36
37/// @name Types
38/// @{
39public:
40
41 /// @brief A mapping of Values to slot numbers
42 typedef std::map<const Value*, unsigned> ValueMap;
43 typedef std::map<const Type*, unsigned> TypeMap;
44
45 /// @brief A plane with next slot number and ValueMap
46 struct ValuePlane {
47 unsigned next_slot; ///< The next slot number to use
48 ValueMap map; ///< The map of Value* -> unsigned
49 ValuePlane() { next_slot = 0; } ///< Make sure we start at 0
50 };
51
52 struct TypePlane {
53 unsigned next_slot;
54 TypeMap map;
55 TypePlane() { next_slot = 0; }
56 void clear() { map.clear(); next_slot = 0; }
57 };
58
59 /// @brief The map of planes by Type
60 typedef std::map<const Type*, ValuePlane> TypedPlanes;
61
62/// @}
63/// @name Constructors
64/// @{
65public:
66 /// @brief Construct from a module
67 SlotMachine(const Module *M );
68
69/// @}
70/// @name Accessors
71/// @{
72public:
73 /// Return the slot number of the specified value in it's type
74 /// plane. Its an error to ask for something not in the SlotMachine.
75 /// Its an error to ask for a Type*
76 int getSlot(const Value *V);
77 int getSlot(const Type*Ty);
78
79 /// Determine if a Value has a slot or not
80 bool hasSlot(const Value* V);
81 bool hasSlot(const Type* Ty);
82
83/// @}
84/// @name Mutators
85/// @{
86public:
87 /// If you'd like to deal with a function instead of just a module, use
88 /// this method to get its data into the SlotMachine.
89 void incorporateFunction(const Function *F) {
90 TheFunction = F;
91 FunctionProcessed = false;
92 }
93
94 /// After calling incorporateFunction, use this method to remove the
95 /// most recently incorporated function from the SlotMachine. This
96 /// will reset the state of the machine back to just the module contents.
97 void purgeFunction();
98
99/// @}
100/// @name Implementation Details
101/// @{
102private:
103 /// Values can be crammed into here at will. If they haven't
104 /// been inserted already, they get inserted, otherwise they are ignored.
105 /// Either way, the slot number for the Value* is returned.
106 unsigned createSlot(const Value *V);
107 unsigned createSlot(const Type* Ty);
108
109 /// Insert a value into the value table. Return the slot number
110 /// that it now occupies. BadThings(TM) will happen if you insert a
111 /// Value that's already been inserted.
112 unsigned insertValue( const Value *V );
113 unsigned insertValue( const Type* Ty);
114
115 /// Add all of the module level global variables (and their initializers)
116 /// and function declarations, but not the contents of those functions.
117 void processModule();
118
119 /// Add all of the functions arguments, basic blocks, and instructions
120 void processFunction();
121
122 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
123 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
124
125/// @}
126/// @name Data
127/// @{
128public:
129
130 /// @brief The module for which we are holding slot numbers
131 const Module* TheModule;
132
133 /// @brief The function for which we are holding slot numbers
134 const Function* TheFunction;
135 bool FunctionProcessed;
136
137 /// @brief The TypePlanes map for the module level data
138 TypedPlanes mMap;
139 TypePlane mTypes;
140
141 /// @brief The TypePlanes map for the function level data
142 TypedPlanes fMap;
143 TypePlane fTypes;
144
145/// @}
146
147};
148
149typedef std::vector<const Type*> TypeList;
150typedef std::map<const Type*,std::string> TypeMap;
151typedef std::map<const Value*,std::string> ValueMap;
152
153void WriteAsOperandInternal(std::ostream &Out, const Value *V,
154 bool PrintName, TypeMap &TypeTable,
155 SlotMachine *Machine);
156
157void WriteAsOperandInternal(std::ostream &Out, const Type *T,
158 bool PrintName, TypeMap& TypeTable,
159 SlotMachine *Machine);
160
161const Module *getModuleFromVal(const Value *V) {
162 if (const Argument *MA = dyn_cast<Argument>(V))
163 return MA->getParent() ? MA->getParent()->getParent() : 0;
164 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
165 return BB->getParent() ? BB->getParent()->getParent() : 0;
166 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
167 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
168 return M ? M->getParent() : 0;
169 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
170 return GV->getParent();
171 return 0;
172}
173
174// getLLVMName - Turn the specified string into an 'LLVM name', which is either
175// prefixed with % (if the string only contains simple characters) or is
176// surrounded with ""'s (if it has special chars in it).
177std::string getLLVMName(const std::string &Name,
178 bool prefixName = true) {
179 assert(!Name.empty() && "Cannot get empty name!");
180
181 // First character cannot start with a number...
182 if (Name[0] >= '0' && Name[0] <= '9')
183 return "\"" + Name + "\"";
184
185 // Scan to see if we have any characters that are not on the "white list"
186 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
187 char C = Name[i];
188 assert(C != '"' && "Illegal character in LLVM value name!");
189 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
190 C != '-' && C != '.' && C != '_')
191 return "\"" + Name + "\"";
192 }
193
194 // If we get here, then the identifier is legal to use as a "VarID".
195 if (prefixName)
196 return "%"+Name;
197 else
198 return Name;
199}
200
201
202/// fillTypeNameTable - If the module has a symbol table, take all global types
203/// and stuff their names into the TypeNames map.
204///
205void fillTypeNameTable(const Module *M, TypeMap& TypeNames) {
206 if (!M) return;
207 const SymbolTable &ST = M->getSymbolTable();
208 SymbolTable::type_const_iterator TI = ST.type_begin();
209 for (; TI != ST.type_end(); ++TI ) {
210 // As a heuristic, don't insert pointer to primitive types, because
211 // they are used too often to have a single useful name.
212 //
213 const Type *Ty = cast<Type>(TI->second);
214 if (!isa<PointerType>(Ty) ||
215 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
216 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
217 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
218 }
219}
220
221void calcTypeName(const Type *Ty,
222 std::vector<const Type *> &TypeStack,
223 TypeMap& TypeNames,
224 std::string & Result){
225 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
226 Result += Ty->getDescription(); // Base case
227 return;
228 }
229
230 // Check to see if the type is named.
231 TypeMap::iterator I = TypeNames.find(Ty);
232 if (I != TypeNames.end()) {
233 Result += I->second;
234 return;
235 }
236
237 if (isa<OpaqueType>(Ty)) {
238 Result += "opaque";
239 return;
240 }
241
242 // Check to see if the Type is already on the stack...
243 unsigned Slot = 0, CurSize = TypeStack.size();
244 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
245
246 // This is another base case for the recursion. In this case, we know
247 // that we have looped back to a type that we have previously visited.
248 // Generate the appropriate upreference to handle this.
249 if (Slot < CurSize) {
250 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
251 return;
252 }
253
254 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
255
256 switch (Ty->getTypeID()) {
257 case Type::FunctionTyID: {
258 const FunctionType *FTy = cast<FunctionType>(Ty);
259 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
260 Result += " (";
261 for (FunctionType::param_iterator I = FTy->param_begin(),
262 E = FTy->param_end(); I != E; ++I) {
263 if (I != FTy->param_begin())
264 Result += ", ";
265 calcTypeName(*I, TypeStack, TypeNames, Result);
266 }
267 if (FTy->isVarArg()) {
268 if (FTy->getNumParams()) Result += ", ";
269 Result += "...";
270 }
271 Result += ")";
272 break;
273 }
274 case Type::StructTyID: {
275 const StructType *STy = cast<StructType>(Ty);
276 Result += "{ ";
277 for (StructType::element_iterator I = STy->element_begin(),
278 E = STy->element_end(); I != E; ++I) {
279 if (I != STy->element_begin())
280 Result += ", ";
281 calcTypeName(*I, TypeStack, TypeNames, Result);
282 }
283 Result += " }";
284 break;
285 }
286 case Type::PointerTyID:
287 calcTypeName(cast<PointerType>(Ty)->getElementType(),
288 TypeStack, TypeNames, Result);
289 Result += "*";
290 break;
291 case Type::ArrayTyID: {
292 const ArrayType *ATy = cast<ArrayType>(Ty);
293 Result += "[" + utostr(ATy->getNumElements()) + " x ";
294 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
295 Result += "]";
296 break;
297 }
298 case Type::PackedTyID: {
299 const PackedType *PTy = cast<PackedType>(Ty);
300 Result += "<" + utostr(PTy->getNumElements()) + " x ";
301 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
302 Result += ">";
303 break;
304 }
305 case Type::OpaqueTyID:
306 Result += "opaque";
307 break;
308 default:
309 Result += "<unrecognized-type>";
310 }
311
312 TypeStack.pop_back(); // Remove self from stack...
313 return;
314}
315
316
317/// printTypeInt - The internal guts of printing out a type that has a
318/// potentially named portion.
319///
320std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,TypeMap&TypeNames){
321 // Primitive types always print out their description, regardless of whether
322 // they have been named or not.
323 //
324 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
325 return Out << Ty->getDescription();
326
327 // Check to see if the type is named.
328 TypeMap::iterator I = TypeNames.find(Ty);
329 if (I != TypeNames.end()) return Out << I->second;
330
331 // Otherwise we have a type that has not been named but is a derived type.
332 // Carefully recurse the type hierarchy to print out any contained symbolic
333 // names.
334 //
335 std::vector<const Type *> TypeStack;
336 std::string TypeName;
337 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
338 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
339 return (Out << TypeName);
340}
341
342
343/// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
344/// type, iff there is an entry in the modules symbol table for the specified
345/// type or one of it's component types. This is slower than a simple x << Type
346///
347std::ostream &WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
348 const Module *M) {
349 Out << ' ';
350
351 // If they want us to print out a type, attempt to make it symbolic if there
352 // is a symbol table in the module...
353 if (M) {
354 TypeMap TypeNames;
355 fillTypeNameTable(M, TypeNames);
356
357 return printTypeInt(Out, Ty, TypeNames);
358 } else {
359 return Out << Ty->getDescription();
360 }
361}
362
363// PrintEscapedString - Print each character of the specified string, escaping
364// it if it is not printable or if it is an escape char.
365void PrintEscapedString(const std::string &Str, std::ostream &Out) {
366 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
367 unsigned char C = Str[i];
368 if (isprint(C) && C != '"' && C != '\\') {
369 Out << C;
370 } else {
371 Out << '\\'
372 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
373 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
374 }
375 }
376}
377
378/// @brief Internal constant writer.
379void WriteConstantInternal(std::ostream &Out, const Constant *CV,
380 bool PrintName,
381 TypeMap& TypeTable,
382 SlotMachine *Machine) {
383 const int IndentSize = 4;
384 static std::string Indent = "\n";
385 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
386 Out << (CB == ConstantBool::True ? "true" : "false");
387 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
388 Out << CI->getValue();
389 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
390 Out << CI->getValue();
391 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
392 // We would like to output the FP constant value in exponential notation,
393 // but we cannot do this if doing so will lose precision. Check here to
394 // make sure that we only output it in exponential format if we can parse
395 // the value back and get the same value.
396 //
397 std::string StrVal = ftostr(CFP->getValue());
398
399 // Check to make sure that the stringized number is not some string like
400 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
401 // the string matches the "[-+]?[0-9]" regex.
402 //
403 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
404 ((StrVal[0] == '-' || StrVal[0] == '+') &&
405 (StrVal[1] >= '0' && StrVal[1] <= '9')))
406 // Reparse stringized version!
407 if (atof(StrVal.c_str()) == CFP->getValue()) {
408 Out << StrVal;
409 return;
410 }
411
412 // Otherwise we could not reparse it to exactly the same value, so we must
413 // output the string in hexadecimal format!
414 assert(sizeof(double) == sizeof(uint64_t) &&
415 "assuming that double is 64 bits!");
416 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
417
418 } else if (isa<ConstantAggregateZero>(CV)) {
419 Out << "zeroinitializer";
420 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
421 // As a special case, print the array as a string if it is an array of
422 // ubytes or an array of sbytes with positive values.
423 //
424 const Type *ETy = CA->getType()->getElementType();
425 if (CA->isString()) {
426 Out << "c\"";
427 PrintEscapedString(CA->getAsString(), Out);
428 Out << "\"";
429
430 } else { // Cannot output in string format...
431 Out << '[';
432 if (CA->getNumOperands()) {
433 Out << ' ';
434 printTypeInt(Out, ETy, TypeTable);
435 WriteAsOperandInternal(Out, CA->getOperand(0),
436 PrintName, TypeTable, Machine);
437 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
438 Out << ", ";
439 printTypeInt(Out, ETy, TypeTable);
440 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
441 TypeTable, Machine);
442 }
443 }
444 Out << " ]";
445 }
446 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
447 Out << '{';
448 unsigned N = CS->getNumOperands();
449 if (N) {
450 if (N > 2) {
451 Indent += std::string(IndentSize, ' ');
452 Out << Indent;
453 } else {
454 Out << ' ';
455 }
456 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
457
458 WriteAsOperandInternal(Out, CS->getOperand(0),
459 PrintName, TypeTable, Machine);
460
461 for (unsigned i = 1; i < N; i++) {
462 Out << ", ";
463 if (N > 2) Out << Indent;
464 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
465
466 WriteAsOperandInternal(Out, CS->getOperand(i),
467 PrintName, TypeTable, Machine);
468 }
469 if (N > 2) Indent.resize(Indent.size() - IndentSize);
470 }
471
472 Out << " }";
473 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
474 const Type *ETy = CP->getType()->getElementType();
475 assert(CP->getNumOperands() > 0 &&
476 "Number of operands for a PackedConst must be > 0");
477 Out << '<';
478 Out << ' ';
479 printTypeInt(Out, ETy, TypeTable);
480 WriteAsOperandInternal(Out, CP->getOperand(0),
481 PrintName, TypeTable, Machine);
482 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
483 Out << ", ";
484 printTypeInt(Out, ETy, TypeTable);
485 WriteAsOperandInternal(Out, CP->getOperand(i), PrintName,
486 TypeTable, Machine);
487 }
488 Out << " >";
489 } else if (isa<ConstantPointerNull>(CV)) {
490 Out << "null";
491
492 } else if (isa<UndefValue>(CV)) {
493 Out << "undef";
494
495 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
496 Out << CE->getOpcodeName() << " (";
497
498 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
499 printTypeInt(Out, (*OI)->getType(), TypeTable);
500 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
501 if (OI+1 != CE->op_end())
502 Out << ", ";
503 }
504
505 if (CE->getOpcode() == Instruction::Cast) {
506 Out << " to ";
507 printTypeInt(Out, CE->getType(), TypeTable);
508 }
509 Out << ')';
510
511 } else {
512 Out << "<placeholder or erroneous Constant>";
513 }
514}
515
516
517/// WriteAsOperand - Write the name of the specified value out to the specified
518/// ostream. This can be useful when you just want to print int %reg126, not
519/// the whole instruction that generated it.
520///
521void WriteAsOperandInternal(std::ostream &Out, const Value *V,
522 bool PrintName, TypeMap& TypeTable,
523 SlotMachine *Machine) {
524 Out << ' ';
525 if ((PrintName || isa<GlobalValue>(V)) && V->hasName())
526 Out << getLLVMName(V->getName());
527 else {
528 const Constant *CV = dyn_cast<Constant>(V);
529 if (CV && !isa<GlobalValue>(CV)) {
530 WriteConstantInternal(Out, CV, PrintName, TypeTable, Machine);
531 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
532 Out << "asm ";
533 if (IA->hasSideEffects())
534 Out << "sideeffect ";
535 Out << '"';
536 PrintEscapedString(IA->getAsmString(), Out);
537 Out << "\", \"";
538 PrintEscapedString(IA->getConstraintString(), Out);
539 Out << '"';
540 } else {
541 int Slot = Machine->getSlot(V);
542 if (Slot != -1)
543 Out << '%' << Slot;
544 else
545 Out << "<badref>";
546 }
547 }
548}
549
550/// WriteAsOperand - Write the name of the specified value out to the specified
551/// ostream. This can be useful when you just want to print int %reg126, not
552/// the whole instruction that generated it.
553///
554std::ostream &WriteAsOperand(std::ostream &Out, const Value *V,
555 bool PrintType, bool PrintName,
556 const Module *Context) {
557 TypeMap TypeNames;
558 if (Context == 0) Context = getModuleFromVal(V);
559
560 if (Context)
561 fillTypeNameTable(Context, TypeNames);
562
563 if (PrintType)
564 printTypeInt(Out, V->getType(), TypeNames);
565
566 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
567 return Out;
568}
569
570/// WriteAsOperandInternal - Write the name of the specified value out to
571/// the specified ostream. This can be useful when you just want to print
572/// int %reg126, not the whole instruction that generated it.
573///
574void WriteAsOperandInternal(std::ostream &Out, const Type *T,
575 bool PrintName, TypeMap& TypeTable,
576 SlotMachine *Machine) {
577 Out << ' ';
578 int Slot = Machine->getSlot(T);
579 if (Slot != -1)
580 Out << '%' << Slot;
581 else
582 Out << "<badref>";
583}
584
585/// WriteAsOperand - Write the name of the specified value out to the specified
586/// ostream. This can be useful when you just want to print int %reg126, not
587/// the whole instruction that generated it.
588///
589std::ostream &WriteAsOperand(std::ostream &Out, const Type *Ty,
590 bool PrintType, bool PrintName,
591 const Module *Context) {
592 TypeMap TypeNames;
593 assert(Context != 0 && "Can't write types as operand without module context");
594
595 fillTypeNameTable(Context, TypeNames);
596
597 // if (PrintType)
598 // printTypeInt(Out, V->getType(), TypeNames);
599
600 printTypeInt(Out, Ty, TypeNames);
601
602 WriteAsOperandInternal(Out, Ty, PrintName, TypeNames, 0);
603 return Out;
604}
605
606class CppWriter {
607 std::ostream &Out;
608 SlotMachine &Machine;
609 const Module *TheModule;
610 unsigned long uniqueNum;
611 TypeMap TypeNames;
612 ValueMap ValueNames;
613 TypeMap UnresolvedTypes;
614 TypeList TypeStack;
615
616public:
617 inline CppWriter(std::ostream &o, SlotMachine &Mac, const Module *M)
618 : Out(o), Machine(Mac), TheModule(M), uniqueNum(0), TypeNames(),
619 ValueNames(), UnresolvedTypes(), TypeStack() { }
620
621 inline void write(const Module *M) { printModule(M); }
622 inline void write(const GlobalVariable *G) { printGlobal(G); }
623 inline void write(const Function *F) { printFunction(F); }
624 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
625 inline void write(const Instruction *I) { printInstruction(*I); }
626 inline void write(const Constant *CPV) { printConstant(CPV); }
627 inline void write(const Type *Ty) { printType(Ty); }
628
629 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
630
631 const Module* getModule() { return TheModule; }
632
633private:
634 void printModule(const Module *M);
635 void printTypes(const Module* M);
636 void printConstants(const Module* M);
637 void printConstant(const Constant *CPV);
638 void printGlobal(const GlobalVariable *GV);
639 void printFunction(const Function *F);
640 void printArgument(const Argument *FA);
641 void printBasicBlock(const BasicBlock *BB);
642 void printInstruction(const Instruction &I);
643 void printSymbolTable(const SymbolTable &ST);
644 void printLinkageType(GlobalValue::LinkageTypes LT);
645 void printCallingConv(unsigned cc);
646
647
648 // printType - Go to extreme measures to attempt to print out a short,
649 // symbolic version of a type name.
650 //
651 std::ostream &printType(const Type *Ty) {
652 return printTypeInt(Out, Ty, TypeNames);
653 }
654
655 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
656 // without considering any symbolic types that we may have equal to it.
657 //
658 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
659
660 // printInfoComment - Print a little comment after the instruction indicating
661 // which slot it occupies.
662 void printInfoComment(const Value &V);
663
664 std::string getCppName(const Type* val);
665 std::string getCppName(const Value* val);
666 inline void printCppName(const Value* val);
667 inline void printCppName(const Type* val);
668 bool isOnStack(const Type*) const;
669 inline void printTypeDef(const Type* Ty);
670 bool printTypeDefInternal(const Type* Ty);
671};
672
673std::string
674CppWriter::getCppName(const Value* val) {
675 std::string name;
676 ValueMap::iterator I = ValueNames.find(val);
677 if (I != ValueNames.end()) {
678 name = I->second;
679 } else {
680 const char* prefix;
681 switch (val->getType()->getTypeID()) {
682 case Type::VoidTyID: prefix = "void_"; break;
683 case Type::BoolTyID: prefix = "bool_"; break;
684 case Type::UByteTyID: prefix = "ubyte_"; break;
685 case Type::SByteTyID: prefix = "sbyte_"; break;
686 case Type::UShortTyID: prefix = "ushort_"; break;
687 case Type::ShortTyID: prefix = "short_"; break;
688 case Type::UIntTyID: prefix = "uint_"; break;
689 case Type::IntTyID: prefix = "int_"; break;
690 case Type::ULongTyID: prefix = "ulong_"; break;
691 case Type::LongTyID: prefix = "long_"; break;
692 case Type::FloatTyID: prefix = "float_"; break;
693 case Type::DoubleTyID: prefix = "double_"; break;
694 case Type::LabelTyID: prefix = "label_"; break;
695 case Type::FunctionTyID: prefix = "func_"; break;
696 case Type::StructTyID: prefix = "struct_"; break;
697 case Type::ArrayTyID: prefix = "array_"; break;
698 case Type::PointerTyID: prefix = "ptr_"; break;
699 case Type::PackedTyID: prefix = "packed_"; break;
700 default: prefix = "other_"; break;
701 }
702 name = ValueNames[val] = std::string(prefix) +
703 (val->hasName() ? val->getName() : utostr(uniqueNum++));
704 }
705 return name;
706}
707
708void
709CppWriter::printCppName(const Value* val) {
710 PrintEscapedString(getCppName(val),Out);
711}
712
713void
714CppWriter::printCppName(const Type* Ty)
715{
716 PrintEscapedString(getCppName(Ty),Out);
717}
718
719// Gets the C++ name for a type. Returns true if we already saw the type,
720// false otherwise.
721//
722inline const std::string*
723findTypeName(const SymbolTable& ST, const Type* Ty)
724{
725 SymbolTable::type_const_iterator TI = ST.type_begin();
726 SymbolTable::type_const_iterator TE = ST.type_end();
727 for (;TI != TE; ++TI)
728 if (TI->second == Ty)
729 return &(TI->first);
730 return 0;
731}
732
733std::string
734CppWriter::getCppName(const Type* Ty)
735{
736 // First, handle the primitive types .. easy
737 if (Ty->isPrimitiveType()) {
738 switch (Ty->getTypeID()) {
739 case Type::VoidTyID: return "Type::VoidTy";
740 case Type::BoolTyID: return "Type::BoolTy";
741 case Type::UByteTyID: return "Type::UByteTy";
742 case Type::SByteTyID: return "Type::SByteTy";
743 case Type::UShortTyID: return "Type::UShortTy";
744 case Type::ShortTyID: return "Type::ShortTy";
745 case Type::UIntTyID: return "Type::UIntTy";
746 case Type::IntTyID: return "Type::IntTy";
747 case Type::ULongTyID: return "Type::ULongTy";
748 case Type::LongTyID: return "Type::LongTy";
749 case Type::FloatTyID: return "Type::FloatTy";
750 case Type::DoubleTyID: return "Type::DoubleTy";
751 case Type::LabelTyID: return "Type::LabelTy";
752 default:
753 assert(!"Can't get here");
754 break;
755 }
756 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
757 }
758
759 // Now, see if we've seen the type before and return that
760 TypeMap::iterator I = TypeNames.find(Ty);
761 if (I != TypeNames.end())
762 return I->second;
763
764 // Okay, let's build a new name for this type. Start with a prefix
765 const char* prefix = 0;
766 switch (Ty->getTypeID()) {
767 case Type::FunctionTyID: prefix = "FuncTy_"; break;
768 case Type::StructTyID: prefix = "StructTy_"; break;
769 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
770 case Type::PointerTyID: prefix = "PointerTy_"; break;
771 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
772 case Type::PackedTyID: prefix = "PackedTy_"; break;
773 default: prefix = "OtherTy_"; break; // prevent breakage
774 }
775
776 // See if the type has a name in the symboltable and build accordingly
777 const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
778 std::string name;
779 if (tName)
780 name = std::string(prefix) + *tName;
781 else
782 name = std::string(prefix) + utostr(uniqueNum++);
783
784 // Save the name
785 return TypeNames[Ty] = name;
786}
787
788/// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
789/// without considering any symbolic types that we may have equal to it.
790///
791std::ostream &CppWriter::printTypeAtLeastOneLevel(const Type *Ty) {
792 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
793 printType(FTy->getReturnType()) << " (";
794 for (FunctionType::param_iterator I = FTy->param_begin(),
795 E = FTy->param_end(); I != E; ++I) {
796 if (I != FTy->param_begin())
797 Out << ", ";
798 printType(*I);
799 }
800 if (FTy->isVarArg()) {
801 if (FTy->getNumParams()) Out << ", ";
802 Out << "...";
803 }
804 Out << ')';
805 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
806 Out << "{ ";
807 for (StructType::element_iterator I = STy->element_begin(),
808 E = STy->element_end(); I != E; ++I) {
809 if (I != STy->element_begin())
810 Out << ", ";
811 printType(*I);
812 }
813 Out << " }";
814 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
815 printType(PTy->getElementType()) << '*';
816 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
817 Out << '[' << ATy->getNumElements() << " x ";
818 printType(ATy->getElementType()) << ']';
819 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
820 Out << '<' << PTy->getNumElements() << " x ";
821 printType(PTy->getElementType()) << '>';
822 }
823 else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
824 Out << "opaque";
825 } else {
826 if (!Ty->isPrimitiveType())
827 Out << "<unknown derived type>";
828 printType(Ty);
829 }
830 return Out;
831}
832
833
834void CppWriter::writeOperand(const Value *Operand, bool PrintType,
835 bool PrintName) {
836 if (Operand != 0) {
837 if (PrintType) { Out << ' '; printType(Operand->getType()); }
838 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Machine);
839 } else {
840 Out << "<null operand!>";
841 }
842}
843
844
845void CppWriter::printModule(const Module *M) {
846 Out << "\n// Module Construction\n";
847 Out << "Module* mod = new Module(\"";
848 PrintEscapedString(M->getModuleIdentifier(),Out);
849 Out << "\");\n";
850 Out << "mod->setEndianness(";
851 switch (M->getEndianness()) {
852 case Module::LittleEndian: Out << "Module::LittleEndian);\n"; break;
853 case Module::BigEndian: Out << "Module::BigEndian);\n"; break;
854 case Module::AnyEndianness:Out << "Module::AnyEndianness);\n"; break;
855 }
856 Out << "mod->setPointerSize(";
857 switch (M->getPointerSize()) {
858 case Module::Pointer32: Out << "Module::Pointer32);\n"; break;
859 case Module::Pointer64: Out << "Module::Pointer64);\n"; break;
860 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);\n"; break;
861 }
862 if (!M->getTargetTriple().empty())
863 Out << "mod->setTargetTriple(\"" << M->getTargetTriple() << "\");\n";
864
865 if (!M->getModuleInlineAsm().empty()) {
866 Out << "mod->setModuleInlineAsm(\"";
867 PrintEscapedString(M->getModuleInlineAsm(),Out);
868 Out << "\");\n";
869 }
870
871 // Loop over the dependent libraries and emit them.
872 Module::lib_iterator LI = M->lib_begin();
873 Module::lib_iterator LE = M->lib_end();
874 while (LI != LE) {
875 Out << "mod->addLibrary(\"" << *LI << "\");\n";
876 ++LI;
877 }
878
879 // Print out all the type definitions
880 Out << "\n// Type Definitions\n";
881 printTypes(M);
882
883 // Print out all the constants declarations
884 Out << "\n// Constants Construction\n";
885 printConstants(M);
886
887 // Process the global variables
888 Out << "\n// Global Variable Construction\n";
889 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
890 I != E; ++I) {
891 printGlobal(I);
892 }
893
894 // Output all of the functions.
895 Out << "\n// Function Construction\n";
896 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
897 printFunction(I);
898}
899
900void
901CppWriter::printCallingConv(unsigned cc){
902 // Print the calling convention.
903 switch (cc) {
904 default:
905 case CallingConv::C: Out << "CallingConv::C"; break;
906 case CallingConv::CSRet: Out << "CallingConv::CSRet"; break;
907 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
908 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
909 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
910 }
911}
912
913void
914CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
915 switch (LT) {
916 case GlobalValue::InternalLinkage:
917 Out << "GlobalValue::InternalLinkage"; break;
918 case GlobalValue::LinkOnceLinkage:
919 Out << "GlobalValue::LinkOnceLinkage "; break;
920 case GlobalValue::WeakLinkage:
921 Out << "GlobalValue::WeakLinkage"; break;
922 case GlobalValue::AppendingLinkage:
923 Out << "GlobalValue::AppendingLinkage"; break;
924 case GlobalValue::ExternalLinkage:
925 Out << "GlobalValue::ExternalLinkage"; break;
926 case GlobalValue::GhostLinkage:
927 Out << "GlobalValue::GhostLinkage"; break;
928 }
929}
930void CppWriter::printGlobal(const GlobalVariable *GV) {
931 Out << "\n";
932 Out << "GlobalVariable* ";
933 printCppName(GV);
934 Out << " = new GlobalVariable(\n";
935 Out << " /*Type=*/";
936 printCppName(GV->getType()->getElementType());
937 Out << ",\n";
938 Out << " /*isConstant=*/" << (GV->isConstant()?"true":"false")
939 << ",\n /*Linkage=*/";
940 printLinkageType(GV->getLinkage());
941 Out << ",\n /*Initializer=*/";
942 if (GV->hasInitializer()) {
943 printCppName(GV->getInitializer());
944 } else {
945 Out << "0";
946 }
947 Out << ",\n /*Name=*/\"";
948 PrintEscapedString(GV->getName(),Out);
949 Out << "\",\n mod);\n";
950
951 if (GV->hasSection()) {
952 printCppName(GV);
953 Out << "->setSection(\"";
954 PrintEscapedString(GV->getSection(),Out);
955 Out << "\");\n";
956 }
957 if (GV->getAlignment()) {
958 printCppName(GV);
959 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");\n";
960 };
961}
962
963bool
964CppWriter::isOnStack(const Type* Ty) const {
965 TypeList::const_iterator TI =
966 std::find(TypeStack.begin(),TypeStack.end(),Ty);
967 return TI != TypeStack.end();
968}
969
970// Prints a type definition. Returns true if it could not resolve all the types
971// in the definition but had to use a forward reference.
972void
973CppWriter::printTypeDef(const Type* Ty) {
974 assert(TypeStack.empty());
975 TypeStack.clear();
976 printTypeDefInternal(Ty);
977 assert(TypeStack.empty());
978 // early resolve as many unresolved types as possible. Search the unresolved
979 // types map for the type we just printed. Now that its definition is complete
980 // we can resolve any preview references to it. This prevents a cascade of
981 // unresolved types.
982 TypeMap::iterator I = UnresolvedTypes.find(Ty);
983 if (I != UnresolvedTypes.end()) {
984 Out << "cast<OpaqueType>(" << I->second
985 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");\n";
986 Out << I->second << " = cast<";
987 switch (Ty->getTypeID()) {
988 case Type::FunctionTyID: Out << "FunctionType"; break;
989 case Type::ArrayTyID: Out << "ArrayType"; break;
990 case Type::StructTyID: Out << "StructType"; break;
991 case Type::PackedTyID: Out << "PackedType"; break;
992 case Type::PointerTyID: Out << "PointerType"; break;
993 case Type::OpaqueTyID: Out << "OpaqueType"; break;
994 default: Out << "NoSuchDerivedType"; break;
995 }
996 Out << ">(" << I->second << "_fwd.get());\n";
997 UnresolvedTypes.erase(I);
998 }
999 Out << "\n";
1000}
1001
1002bool
1003CppWriter::printTypeDefInternal(const Type* Ty) {
1004 // We don't print definitions for primitive types
1005 if (Ty->isPrimitiveType())
1006 return false;
1007
1008 // Determine if the name is in the name list before we modify that list.
1009 TypeMap::const_iterator TNI = TypeNames.find(Ty);
1010
1011 // Everything below needs the name for the type so get it now
1012 std::string typeName(getCppName(Ty));
1013
1014 // Search the type stack for recursion. If we find it, then generate this
1015 // as an OpaqueType, but make sure not to do this multiple times because
1016 // the type could appear in multiple places on the stack. Once the opaque
1017 // definition is issues, it must not be re-issued. Consequently we have to
1018 // check the UnresolvedTypes list as well.
1019 if (isOnStack(Ty)) {
1020 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
1021 if (I == UnresolvedTypes.end()) {
1022 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();\n";
1023 UnresolvedTypes[Ty] = typeName;
1024 return true;
1025 }
1026 }
1027
1028 // Avoid printing things we have already printed. Since TNI was obtained
1029 // before the name was inserted with getCppName and because we know the name
1030 // is not on the stack (currently being defined), we can surmise here that if
1031 // we got the name we've also already emitted its definition.
1032 if (TNI != TypeNames.end())
1033 return false;
1034
1035 // We're going to print a derived type which, by definition, contains other
1036 // types. So, push this one we're printing onto the type stack to assist with
1037 // recursive definitions.
1038 TypeStack.push_back(Ty); // push on type stack
1039 bool didRecurse = false;
1040
1041 // Print the type definition
1042 switch (Ty->getTypeID()) {
1043 case Type::FunctionTyID: {
1044 const FunctionType* FT = cast<FunctionType>(Ty);
1045 Out << "std::vector<const Type*>" << typeName << "_args;\n";
1046 FunctionType::param_iterator PI = FT->param_begin();
1047 FunctionType::param_iterator PE = FT->param_end();
1048 for (; PI != PE; ++PI) {
1049 const Type* argTy = static_cast<const Type*>(*PI);
1050 bool isForward = printTypeDefInternal(argTy);
1051 std::string argName(getCppName(argTy));
1052 Out << typeName << "_args.push_back(" << argName;
1053 if (isForward)
1054 Out << "_fwd";
1055 Out << ");\n";
1056 }
1057 bool isForward = printTypeDefInternal(FT->getReturnType());
1058 std::string retTypeName(getCppName(FT->getReturnType()));
1059 Out << "FunctionType* " << typeName << " = FunctionType::get(\n"
1060 << " /*Result=*/" << retTypeName;
1061 if (isForward)
1062 Out << "_fwd";
1063 Out << ",\n /*Params=*/" << typeName << "_args,\n /*isVarArg=*/"
1064 << (FT->isVarArg() ? "true" : "false") << ");\n";
1065 break;
1066 }
1067 case Type::StructTyID: {
1068 const StructType* ST = cast<StructType>(Ty);
1069 Out << "std::vector<const Type*>" << typeName << "_fields;\n";
1070 StructType::element_iterator EI = ST->element_begin();
1071 StructType::element_iterator EE = ST->element_end();
1072 for (; EI != EE; ++EI) {
1073 const Type* fieldTy = static_cast<const Type*>(*EI);
1074 bool isForward = printTypeDefInternal(fieldTy);
1075 std::string fieldName(getCppName(fieldTy));
1076 Out << typeName << "_fields.push_back(" << fieldName;
1077 if (isForward)
1078 Out << "_fwd";
1079 Out << ");\n";
1080 }
1081 Out << "StructType* " << typeName << " = StructType::get("
1082 << typeName << "_fields);\n";
1083 break;
1084 }
1085 case Type::ArrayTyID: {
1086 const ArrayType* AT = cast<ArrayType>(Ty);
1087 const Type* ET = AT->getElementType();
1088 bool isForward = printTypeDefInternal(ET);
1089 std::string elemName(getCppName(ET));
1090 Out << "ArrayType* " << typeName << " = ArrayType::get("
1091 << elemName << (isForward ? "_fwd" : "")
1092 << ", " << utostr(AT->getNumElements()) << ");\n";
1093 break;
1094 }
1095 case Type::PointerTyID: {
1096 const PointerType* PT = cast<PointerType>(Ty);
1097 const Type* ET = PT->getElementType();
1098 bool isForward = printTypeDefInternal(ET);
1099 std::string elemName(getCppName(ET));
1100 Out << "PointerType* " << typeName << " = PointerType::get("
1101 << elemName << (isForward ? "_fwd" : "") << ");\n";
1102 break;
1103 }
1104 case Type::PackedTyID: {
1105 const PackedType* PT = cast<PackedType>(Ty);
1106 const Type* ET = PT->getElementType();
1107 bool isForward = printTypeDefInternal(ET);
1108 std::string elemName(getCppName(ET));
1109 Out << "PackedType* " << typeName << " = PackedType::get("
1110 << elemName << (isForward ? "_fwd" : "")
1111 << ", " << utostr(PT->getNumElements()) << ");\n";
1112 break;
1113 }
1114 case Type::OpaqueTyID: {
1115 const OpaqueType* OT = cast<OpaqueType>(Ty);
1116 Out << "OpaqueType* " << typeName << " = OpaqueType::get();\n";
1117 break;
1118 }
1119 default:
1120 assert(!"Invalid TypeID");
1121 }
1122
Reid Spencer74e032a2006-05-29 02:58:15 +00001123 // If the type had a name, make sure we recreate it.
1124 const std::string* progTypeName =
1125 findTypeName(TheModule->getSymbolTable(),Ty);
1126 if (progTypeName)
1127 Out << "mod->addTypeName(\"" << *progTypeName << "\", "
1128 << typeName << ");\n";
1129
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001130 // Pop us off the type stack
1131 TypeStack.pop_back();
1132
1133 // We weren't a recursive type
1134 return false;
1135}
1136
1137void
1138CppWriter::printTypes(const Module* M) {
1139 // Add all of the global variables to the value table...
1140 for (Module::const_global_iterator I = TheModule->global_begin(),
1141 E = TheModule->global_end(); I != E; ++I) {
1142 if (I->hasInitializer())
1143 printTypeDef(I->getInitializer()->getType());
1144 printTypeDef(I->getType());
1145 }
1146
1147 // Add all the functions to the table
1148 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
1149 FI != FE; ++FI) {
1150 printTypeDef(FI->getReturnType());
1151 printTypeDef(FI->getFunctionType());
1152 // Add all the function arguments
1153 for(Function::const_arg_iterator AI = FI->arg_begin(),
1154 AE = FI->arg_end(); AI != AE; ++AI) {
1155 printTypeDef(AI->getType());
1156 }
1157
1158 // Add all of the basic blocks and instructions
1159 for (Function::const_iterator BB = FI->begin(),
1160 E = FI->end(); BB != E; ++BB) {
1161 printTypeDef(BB->getType());
1162 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
1163 ++I) {
1164 printTypeDef(I->getType());
1165 }
1166 }
1167 }
1168}
1169
1170void
1171CppWriter::printConstants(const Module* M) {
1172 const SymbolTable& ST = M->getSymbolTable();
1173
1174 // Print the constants, in type plane order.
1175 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
1176 PI != ST.plane_end(); ++PI ) {
1177 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
1178 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
1179
1180 for (; VI != VE; ++VI) {
1181 const Value* V = VI->second;
1182 const Constant *CPV = dyn_cast<Constant>(V) ;
1183 if (CPV && !isa<GlobalValue>(V)) {
1184 printConstant(CPV);
1185 }
1186 }
1187 }
1188
1189 // Add all of the global variables to the value table...
1190 for (Module::const_global_iterator I = TheModule->global_begin(),
1191 E = TheModule->global_end(); I != E; ++I)
1192 if (I->hasInitializer())
1193 printConstant(I->getInitializer());
1194}
1195
1196// printSymbolTable - Run through symbol table looking for constants
1197// and types. Emit their declarations.
1198void CppWriter::printSymbolTable(const SymbolTable &ST) {
1199
1200 // Print the types.
1201 for (SymbolTable::type_const_iterator TI = ST.type_begin();
1202 TI != ST.type_end(); ++TI ) {
1203 Out << "\t" << getLLVMName(TI->first) << " = type ";
1204
1205 // Make sure we print out at least one level of the type structure, so
1206 // that we do not get %FILE = type %FILE
1207 //
1208 printTypeAtLeastOneLevel(TI->second) << "\n";
1209 }
1210
1211}
1212
1213
1214/// printConstant - Print out a constant pool entry...
1215///
1216void CppWriter::printConstant(const Constant *CV) {
1217 const int IndentSize = 2;
1218 static std::string Indent = "\n";
1219 std::string constName(getCppName(CV));
1220 std::string typeName(getCppName(CV->getType()));
1221 if (CV->isNullValue()) {
1222 Out << "Constant* " << constName << " = Constant::getNullValue("
1223 << typeName << ");\n";
1224 return;
1225 }
1226 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
1227 Out << "Constant* " << constName << " = ConstantBool::get("
1228 << (CB == ConstantBool::True ? "true" : "false")
1229 << ");";
1230 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
1231 Out << "Constant* " << constName << " = ConstantSInt::get("
1232 << typeName << ", " << CI->getValue() << ");";
1233 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
1234 Out << "Constant* " << constName << " = ConstantUInt::get("
1235 << typeName << ", " << CI->getValue() << ");";
1236 } else if (isa<ConstantAggregateZero>(CV)) {
1237 Out << "Constant* " << constName << " = ConstantAggregateZero::get("
1238 << typeName << ");";
1239 } else if (isa<ConstantPointerNull>(CV)) {
1240 Out << "Constant* " << constName << " = ConstanPointerNull::get("
1241 << typeName << ");";
1242 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1243 Out << "ConstantFP::get(" << typeName << ", ";
1244 // We would like to output the FP constant value in exponential notation,
1245 // but we cannot do this if doing so will lose precision. Check here to
1246 // make sure that we only output it in exponential format if we can parse
1247 // the value back and get the same value.
1248 //
1249 std::string StrVal = ftostr(CFP->getValue());
1250
1251 // Check to make sure that the stringized number is not some string like
1252 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
1253 // the string matches the "[-+]?[0-9]" regex.
1254 //
1255 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1256 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1257 (StrVal[1] >= '0' && StrVal[1] <= '9')))
1258 // Reparse stringized version!
1259 if (atof(StrVal.c_str()) == CFP->getValue()) {
1260 Out << StrVal;
1261 return;
1262 }
1263
1264 // Otherwise we could not reparse it to exactly the same value, so we must
1265 // output the string in hexadecimal format!
1266 assert(sizeof(double) == sizeof(uint64_t) &&
1267 "assuming that double is 64 bits!");
1268 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue())) << ");";
1269 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1270 if (CA->isString()) {
1271 Out << "Constant* " << constName << " = ConstantArray::get(\"";
1272 PrintEscapedString(CA->getAsString(),Out);
1273 Out << "\");";
1274 } else {
1275 Out << "std::vector<Constant*> " << constName << "_elems;\n";
1276 unsigned N = CA->getNumOperands();
1277 for (unsigned i = 0; i < N; ++i) {
1278 printConstant(CA->getOperand(i));
1279 Out << constName << "_elems.push_back("
1280 << getCppName(CA->getOperand(i)) << ");\n";
1281 }
1282 Out << "Constant* " << constName << " = ConstantArray::get("
1283 << typeName << ", " << constName << "_elems);";
1284 }
1285 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1286 Out << "std::vector<Constant*> " << constName << "_fields;\n";
1287 unsigned N = CS->getNumOperands();
1288 for (unsigned i = 0; i < N; i++) {
1289 printConstant(CS->getOperand(i));
1290 Out << constName << "_fields.push_back("
1291 << getCppName(CA->getOperand(i)) << ");\n";
1292 }
1293 Out << "Constant* " << constName << " = ConstantStruct::get("
1294 << typeName << ", " << constName << "_fields);";
1295 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
1296 Out << "std::vector<Constant*> " << constName << "_elems;\n";
1297 unsigned N = CP->getNumOperands();
1298 for (unsigned i = 0; i < N; ++i) {
1299 printConstant(CP->getOperand(i));
1300 Out << constName << "_elems.push_back("
1301 << getCppName(CP->getOperand(i)) << ");\n";
1302 }
1303 Out << "Constant* " << constName << " = ConstantPacked::get("
1304 << typeName << ", " << constName << "_elems);";
1305 } else if (isa<UndefValue>(CV)) {
1306 Out << "Constant* " << constName << " = UndefValue::get("
1307 << typeName << ");\n";
1308 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1309 Out << CE->getOpcodeName() << " (";
1310
1311 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1312 //printTypeInt(Out, (*OI)->getType(), TypeTable);
1313 //WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
1314 if (OI+1 != CE->op_end())
1315 Out << ", ";
1316 }
1317
1318 if (CE->getOpcode() == Instruction::Cast) {
1319 Out << " to ";
1320 // printTypeInt(Out, CE->getType(), TypeTable);
1321 }
1322 Out << ')';
1323
1324 } else {
1325 Out << "<placeholder or erroneous Constant>";
1326 }
1327 Out << "\n";
1328}
1329
1330/// printFunction - Print all aspects of a function.
1331///
1332void CppWriter::printFunction(const Function *F) {
1333 std::string funcTypeName(getCppName(F->getFunctionType()));
1334
1335 Out << "Function* ";
1336 printCppName(F);
1337 Out << " = new Function(" << funcTypeName << ", " ;
1338 printLinkageType(F->getLinkage());
1339 Out << ", \"" << F->getName() << "\", mod);\n";
1340 printCppName(F);
1341 Out << "->setCallingConv(";
1342 printCallingConv(F->getCallingConv());
1343 Out << ");\n";
1344 if (F->hasSection()) {
1345 printCppName(F);
1346 Out << "->setSection(" << F->getSection() << ");\n";
1347 }
1348 if (F->getAlignment()) {
1349 printCppName(F);
1350 Out << "->setAlignment(" << F->getAlignment() << ");\n";
1351 }
1352
1353 Machine.incorporateFunction(F);
1354
1355 if (!F->isExternal()) {
1356 Out << "{";
1357 // Output all of its basic blocks... for the function
1358 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1359 printBasicBlock(I);
1360 Out << "}\n";
1361 }
1362
1363 Machine.purgeFunction();
1364}
1365
1366/// printArgument - This member is called for every argument that is passed into
1367/// the function. Simply print it out
1368///
1369void CppWriter::printArgument(const Argument *Arg) {
1370 // Insert commas as we go... the first arg doesn't get a comma
1371 if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
1372
1373 // Output type...
1374 printType(Arg->getType());
1375
1376 // Output name, if available...
1377 if (Arg->hasName())
1378 Out << ' ' << getLLVMName(Arg->getName());
1379}
1380
1381/// printBasicBlock - This member is called for each basic block in a method.
1382///
1383void CppWriter::printBasicBlock(const BasicBlock *BB) {
1384 if (BB->hasName()) { // Print out the label if it exists...
1385 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1386 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1387 Out << "\n; <label>:";
1388 int Slot = Machine.getSlot(BB);
1389 if (Slot != -1)
1390 Out << Slot;
1391 else
1392 Out << "<badref>";
1393 }
1394
1395 if (BB->getParent() == 0)
1396 Out << "\t\t; Error: Block without parent!";
1397 else {
1398 if (BB != &BB->getParent()->front()) { // Not the entry block?
1399 // Output predecessors for the block...
1400 Out << "\t\t;";
1401 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1402
1403 if (PI == PE) {
1404 Out << " No predecessors!";
1405 } else {
1406 Out << " preds =";
1407 writeOperand(*PI, false, true);
1408 for (++PI; PI != PE; ++PI) {
1409 Out << ',';
1410 writeOperand(*PI, false, true);
1411 }
1412 }
1413 }
1414 }
1415
1416 Out << "\n";
1417
1418 // Output all of the instructions in the basic block...
1419 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1420 printInstruction(*I);
1421}
1422
1423
1424/// printInfoComment - Print a little comment after the instruction indicating
1425/// which slot it occupies.
1426///
1427void CppWriter::printInfoComment(const Value &V) {
1428 if (V.getType() != Type::VoidTy) {
1429 Out << "\t\t; <";
1430 printType(V.getType()) << '>';
1431
1432 if (!V.hasName()) {
1433 int SlotNum = Machine.getSlot(&V);
1434 if (SlotNum == -1)
1435 Out << ":<badref>";
1436 else
1437 Out << ':' << SlotNum; // Print out the def slot taken.
1438 }
1439 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1440 }
1441}
1442
1443/// printInstruction - This member is called for each Instruction in a function..
1444///
1445void CppWriter::printInstruction(const Instruction &I) {
1446 Out << "\t";
1447
1448 // Print out name if it exists...
1449 if (I.hasName())
1450 Out << getLLVMName(I.getName()) << " = ";
1451
1452 // If this is a volatile load or store, print out the volatile marker.
1453 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1454 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1455 Out << "volatile ";
1456 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1457 // If this is a call, check if it's a tail call.
1458 Out << "tail ";
1459 }
1460
1461 // Print out the opcode...
1462 Out << I.getOpcodeName();
1463
1464 // Print out the type of the operands...
1465 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1466
1467 // Special case conditional branches to swizzle the condition out to the front
1468 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1469 writeOperand(I.getOperand(2), true);
1470 Out << ',';
1471 writeOperand(Operand, true);
1472 Out << ',';
1473 writeOperand(I.getOperand(1), true);
1474
1475 } else if (isa<SwitchInst>(I)) {
1476 // Special case switch statement to get formatting nice and correct...
1477 writeOperand(Operand , true); Out << ',';
1478 writeOperand(I.getOperand(1), true); Out << " [";
1479
1480 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1481 Out << "\n\t\t";
1482 writeOperand(I.getOperand(op ), true); Out << ',';
1483 writeOperand(I.getOperand(op+1), true);
1484 }
1485 Out << "\n\t]";
1486 } else if (isa<PHINode>(I)) {
1487 Out << ' ';
1488 printType(I.getType());
1489 Out << ' ';
1490
1491 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1492 if (op) Out << ", ";
1493 Out << '[';
1494 writeOperand(I.getOperand(op ), false); Out << ',';
1495 writeOperand(I.getOperand(op+1), false); Out << " ]";
1496 }
1497 } else if (isa<ReturnInst>(I) && !Operand) {
1498 Out << " void";
1499 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1500 // Print the calling convention being used.
1501 switch (CI->getCallingConv()) {
1502 case CallingConv::C: break; // default
1503 case CallingConv::CSRet: Out << " csretcc"; break;
1504 case CallingConv::Fast: Out << " fastcc"; break;
1505 case CallingConv::Cold: Out << " coldcc"; break;
1506 default: Out << " cc" << CI->getCallingConv(); break;
1507 }
1508
1509 const PointerType *PTy = cast<PointerType>(Operand->getType());
1510 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1511 const Type *RetTy = FTy->getReturnType();
1512
1513 // If possible, print out the short form of the call instruction. We can
1514 // only do this if the first argument is a pointer to a nonvararg function,
1515 // and if the return type is not a pointer to a function.
1516 //
1517 if (!FTy->isVarArg() &&
1518 (!isa<PointerType>(RetTy) ||
1519 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1520 Out << ' '; printType(RetTy);
1521 writeOperand(Operand, false);
1522 } else {
1523 writeOperand(Operand, true);
1524 }
1525 Out << '(';
1526 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
1527 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1528 Out << ',';
1529 writeOperand(I.getOperand(op), true);
1530 }
1531
1532 Out << " )";
1533 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1534 const PointerType *PTy = cast<PointerType>(Operand->getType());
1535 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1536 const Type *RetTy = FTy->getReturnType();
1537
1538 // Print the calling convention being used.
1539 switch (II->getCallingConv()) {
1540 case CallingConv::C: break; // default
1541 case CallingConv::CSRet: Out << " csretcc"; break;
1542 case CallingConv::Fast: Out << " fastcc"; break;
1543 case CallingConv::Cold: Out << " coldcc"; break;
1544 default: Out << " cc" << II->getCallingConv(); break;
1545 }
1546
1547 // If possible, print out the short form of the invoke instruction. We can
1548 // only do this if the first argument is a pointer to a nonvararg function,
1549 // and if the return type is not a pointer to a function.
1550 //
1551 if (!FTy->isVarArg() &&
1552 (!isa<PointerType>(RetTy) ||
1553 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1554 Out << ' '; printType(RetTy);
1555 writeOperand(Operand, false);
1556 } else {
1557 writeOperand(Operand, true);
1558 }
1559
1560 Out << '(';
1561 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1562 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1563 Out << ',';
1564 writeOperand(I.getOperand(op), true);
1565 }
1566
1567 Out << " )\n\t\t\tto";
1568 writeOperand(II->getNormalDest(), true);
1569 Out << " unwind";
1570 writeOperand(II->getUnwindDest(), true);
1571
1572 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1573 Out << ' ';
1574 printType(AI->getType()->getElementType());
1575 if (AI->isArrayAllocation()) {
1576 Out << ',';
1577 writeOperand(AI->getArraySize(), true);
1578 }
1579 if (AI->getAlignment()) {
1580 Out << ", align " << AI->getAlignment();
1581 }
1582 } else if (isa<CastInst>(I)) {
1583 if (Operand) writeOperand(Operand, true); // Work with broken code
1584 Out << " to ";
1585 printType(I.getType());
1586 } else if (isa<VAArgInst>(I)) {
1587 if (Operand) writeOperand(Operand, true); // Work with broken code
1588 Out << ", ";
1589 printType(I.getType());
1590 } else if (Operand) { // Print the normal way...
1591
1592 // PrintAllTypes - Instructions who have operands of all the same type
1593 // omit the type from all but the first operand. If the instruction has
1594 // different type operands (for example br), then they are all printed.
1595 bool PrintAllTypes = false;
1596 const Type *TheType = Operand->getType();
1597
1598 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1599 // types even if all operands are bools.
1600 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1601 isa<ShuffleVectorInst>(I)) {
1602 PrintAllTypes = true;
1603 } else {
1604 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1605 Operand = I.getOperand(i);
1606 if (Operand->getType() != TheType) {
1607 PrintAllTypes = true; // We have differing types! Print them all!
1608 break;
1609 }
1610 }
1611 }
1612
1613 if (!PrintAllTypes) {
1614 Out << ' ';
1615 printType(TheType);
1616 }
1617
1618 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1619 if (i) Out << ',';
1620 writeOperand(I.getOperand(i), PrintAllTypes);
1621 }
1622 }
1623
1624 printInfoComment(I);
1625 Out << "\n";
1626}
1627
1628
1629//===----------------------------------------------------------------------===//
1630// External Interface declarations
1631//===----------------------------------------------------------------------===//
1632
1633
1634//===----------------------------------------------------------------------===//
1635//===-- SlotMachine Implementation
1636//===----------------------------------------------------------------------===//
1637
1638#if 0
1639#define SC_DEBUG(X) std::cerr << X
1640#else
1641#define SC_DEBUG(X)
1642#endif
1643
1644// Module level constructor. Causes the contents of the Module (sans functions)
1645// to be added to the slot table.
1646SlotMachine::SlotMachine(const Module *M)
1647 : TheModule(M) ///< Saved for lazy initialization.
1648 , mMap()
1649 , mTypes()
1650 , fMap()
1651 , fTypes()
1652{
1653 assert(M != 0 && "Invalid Module");
1654 processModule();
1655}
1656
1657// Iterate through all the global variables, functions, and global
1658// variable initializers and create slots for them.
1659void SlotMachine::processModule() {
1660 // Add all of the global variables to the value table...
1661 for (Module::const_global_iterator I = TheModule->global_begin(), E = TheModule->global_end();
1662 I != E; ++I)
1663 createSlot(I);
1664
1665 // Add all the functions to the table
1666 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
1667 FI != FE; ++FI) {
1668 createSlot(FI);
1669 // Add all the function arguments
1670 for(Function::const_arg_iterator AI = FI->arg_begin(),
1671 AE = FI->arg_end(); AI != AE; ++AI)
1672 createSlot(AI);
1673
1674 // Add all of the basic blocks and instructions
1675 for (Function::const_iterator BB = FI->begin(),
1676 E = FI->end(); BB != E; ++BB) {
1677 createSlot(BB);
1678 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
1679 ++I) {
1680 createSlot(I);
1681 }
1682 }
1683 }
1684}
1685
1686// Process the arguments, basic blocks, and instructions of a function.
1687void SlotMachine::processFunction() {
1688
1689}
1690
1691// Clean up after incorporating a function. This is the only way
1692// to get out of the function incorporation state that affects the
1693// getSlot/createSlot lock. Function incorporation state is indicated
1694// by TheFunction != 0.
1695void SlotMachine::purgeFunction() {
1696 SC_DEBUG("begin purgeFunction!\n");
1697 fMap.clear(); // Simply discard the function level map
1698 fTypes.clear();
1699 TheFunction = 0;
1700 FunctionProcessed = false;
1701 SC_DEBUG("end purgeFunction!\n");
1702}
1703
1704/// Get the slot number for a value. This function will assert if you
1705/// ask for a Value that hasn't previously been inserted with createSlot.
1706/// Types are forbidden because Type does not inherit from Value (any more).
1707int SlotMachine::getSlot(const Value *V) {
1708 assert( V && "Can't get slot for null Value" );
1709 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1710 "Can't insert a non-GlobalValue Constant into SlotMachine");
1711
1712 // Get the type of the value
1713 const Type* VTy = V->getType();
1714
1715 // Find the type plane in the module map
1716 TypedPlanes::const_iterator MI = mMap.find(VTy);
1717
1718 if ( TheFunction ) {
1719 // Lookup the type in the function map too
1720 TypedPlanes::const_iterator FI = fMap.find(VTy);
1721 // If there is a corresponding type plane in the function map
1722 if ( FI != fMap.end() ) {
1723 // Lookup the Value in the function map
1724 ValueMap::const_iterator FVI = FI->second.map.find(V);
1725 // If the value doesn't exist in the function map
1726 if ( FVI == FI->second.map.end() ) {
1727 // Look up the value in the module map.
1728 if (MI == mMap.end()) return -1;
1729 ValueMap::const_iterator MVI = MI->second.map.find(V);
1730 // If we didn't find it, it wasn't inserted
1731 if (MVI == MI->second.map.end()) return -1;
1732 assert( MVI != MI->second.map.end() && "Value not found");
1733 // We found it only at the module level
1734 return MVI->second;
1735
1736 // else the value exists in the function map
1737 } else {
1738 // Return the slot number as the module's contribution to
1739 // the type plane plus the index in the function's contribution
1740 // to the type plane.
1741 if (MI != mMap.end())
1742 return MI->second.next_slot + FVI->second;
1743 else
1744 return FVI->second;
1745 }
1746 }
1747 }
1748
1749 // N.B. Can get here only if either !TheFunction or the function doesn't
1750 // have a corresponding type plane for the Value
1751
1752 // Make sure the type plane exists
1753 if (MI == mMap.end()) return -1;
1754 // Lookup the value in the module's map
1755 ValueMap::const_iterator MVI = MI->second.map.find(V);
1756 // Make sure we found it.
1757 if (MVI == MI->second.map.end()) return -1;
1758 // Return it.
1759 return MVI->second;
1760}
1761
1762/// Get the slot number for a type. This function will assert if you
1763/// ask for a Type that hasn't previously been inserted with createSlot.
1764int SlotMachine::getSlot(const Type *Ty) {
1765 assert( Ty && "Can't get slot for null Type" );
1766
1767 if ( TheFunction ) {
1768 // Lookup the Type in the function map
1769 TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1770 // If the Type doesn't exist in the function map
1771 if ( FTI == fTypes.map.end() ) {
1772 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1773 // If we didn't find it, it wasn't inserted
1774 if (MTI == mTypes.map.end())
1775 return -1;
1776 // We found it only at the module level
1777 return MTI->second;
1778
1779 // else the value exists in the function map
1780 } else {
1781 // Return the slot number as the module's contribution to
1782 // the type plane plus the index in the function's contribution
1783 // to the type plane.
1784 return mTypes.next_slot + FTI->second;
1785 }
1786 }
1787
1788 // N.B. Can get here only if !TheFunction
1789
1790 // Lookup the value in the module's map
1791 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1792 // Make sure we found it.
1793 if (MTI == mTypes.map.end()) return -1;
1794 // Return it.
1795 return MTI->second;
1796}
1797
1798// Create a new slot, or return the existing slot if it is already
1799// inserted. Note that the logic here parallels getSlot but instead
1800// of asserting when the Value* isn't found, it inserts the value.
1801unsigned SlotMachine::createSlot(const Value *V) {
1802 assert( V && "Can't insert a null Value to SlotMachine");
1803 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1804 "Can't insert a non-GlobalValue Constant into SlotMachine");
1805
1806 const Type* VTy = V->getType();
1807
1808 // Just ignore void typed things
1809 if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1810
1811 // Look up the type plane for the Value's type from the module map
1812 TypedPlanes::const_iterator MI = mMap.find(VTy);
1813
1814 if ( TheFunction ) {
1815 // Get the type plane for the Value's type from the function map
1816 TypedPlanes::const_iterator FI = fMap.find(VTy);
1817 // If there is a corresponding type plane in the function map
1818 if ( FI != fMap.end() ) {
1819 // Lookup the Value in the function map
1820 ValueMap::const_iterator FVI = FI->second.map.find(V);
1821 // If the value doesn't exist in the function map
1822 if ( FVI == FI->second.map.end() ) {
1823 // If there is no corresponding type plane in the module map
1824 if ( MI == mMap.end() )
1825 return insertValue(V);
1826 // Look up the value in the module map
1827 ValueMap::const_iterator MVI = MI->second.map.find(V);
1828 // If we didn't find it, it wasn't inserted
1829 if ( MVI == MI->second.map.end() )
1830 return insertValue(V);
1831 else
1832 // We found it only at the module level
1833 return MVI->second;
1834
1835 // else the value exists in the function map
1836 } else {
1837 if ( MI == mMap.end() )
1838 return FVI->second;
1839 else
1840 // Return the slot number as the module's contribution to
1841 // the type plane plus the index in the function's contribution
1842 // to the type plane.
1843 return MI->second.next_slot + FVI->second;
1844 }
1845
1846 // else there is not a corresponding type plane in the function map
1847 } else {
1848 // If the type plane doesn't exists at the module level
1849 if ( MI == mMap.end() ) {
1850 return insertValue(V);
1851 // else type plane exists at the module level, examine it
1852 } else {
1853 // Look up the value in the module's map
1854 ValueMap::const_iterator MVI = MI->second.map.find(V);
1855 // If we didn't find it there either
1856 if ( MVI == MI->second.map.end() )
1857 // Return the slot number as the module's contribution to
1858 // the type plane plus the index of the function map insertion.
1859 return MI->second.next_slot + insertValue(V);
1860 else
1861 return MVI->second;
1862 }
1863 }
1864 }
1865
1866 // N.B. Can only get here if !TheFunction
1867
1868 // If the module map's type plane is not for the Value's type
1869 if ( MI != mMap.end() ) {
1870 // Lookup the value in the module's map
1871 ValueMap::const_iterator MVI = MI->second.map.find(V);
1872 if ( MVI != MI->second.map.end() )
1873 return MVI->second;
1874 }
1875
1876 return insertValue(V);
1877}
1878
1879// Create a new slot, or return the existing slot if it is already
1880// inserted. Note that the logic here parallels getSlot but instead
1881// of asserting when the Value* isn't found, it inserts the value.
1882unsigned SlotMachine::createSlot(const Type *Ty) {
1883 assert( Ty && "Can't insert a null Type to SlotMachine");
1884
1885 if ( TheFunction ) {
1886 // Lookup the Type in the function map
1887 TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1888 // If the type doesn't exist in the function map
1889 if ( FTI == fTypes.map.end() ) {
1890 // Look up the type in the module map
1891 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1892 // If we didn't find it, it wasn't inserted
1893 if ( MTI == mTypes.map.end() )
1894 return insertValue(Ty);
1895 else
1896 // We found it only at the module level
1897 return MTI->second;
1898
1899 // else the value exists in the function map
1900 } else {
1901 // Return the slot number as the module's contribution to
1902 // the type plane plus the index in the function's contribution
1903 // to the type plane.
1904 return mTypes.next_slot + FTI->second;
1905 }
1906 }
1907
1908 // N.B. Can only get here if !TheFunction
1909
1910 // Lookup the type in the module's map
1911 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1912 if ( MTI != mTypes.map.end() )
1913 return MTI->second;
1914
1915 return insertValue(Ty);
1916}
1917
1918// Low level insert function. Minimal checking is done. This
1919// function is just for the convenience of createSlot (above).
1920unsigned SlotMachine::insertValue(const Value *V ) {
1921 assert(V && "Can't insert a null Value into SlotMachine!");
1922 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1923 "Can't insert a non-GlobalValue Constant into SlotMachine");
1924
1925 // If this value does not contribute to a plane (is void)
1926 // or if the value already has a name then ignore it.
1927 if (V->getType() == Type::VoidTy || V->hasName() ) {
1928 SC_DEBUG("ignored value " << *V << "\n");
1929 return 0; // FIXME: Wrong return value
1930 }
1931
1932 const Type *VTy = V->getType();
1933 unsigned DestSlot = 0;
1934
1935 if ( TheFunction ) {
1936 TypedPlanes::iterator I = fMap.find( VTy );
1937 if ( I == fMap.end() )
1938 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1939 DestSlot = I->second.map[V] = I->second.next_slot++;
1940 } else {
1941 TypedPlanes::iterator I = mMap.find( VTy );
1942 if ( I == mMap.end() )
1943 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1944 DestSlot = I->second.map[V] = I->second.next_slot++;
1945 }
1946
1947 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1948 DestSlot << " [");
1949 // G = Global, C = Constant, T = Type, F = Function, o = other
1950 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' :
1951 (isa<Constant>(V) ? 'C' : 'o'))));
1952 SC_DEBUG("]\n");
1953 return DestSlot;
1954}
1955
1956// Low level insert function. Minimal checking is done. This
1957// function is just for the convenience of createSlot (above).
1958unsigned SlotMachine::insertValue(const Type *Ty ) {
1959 assert(Ty && "Can't insert a null Type into SlotMachine!");
1960
1961 unsigned DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1962 SC_DEBUG(" Inserting type [" << DestSlot << "] = " << Ty << "\n");
1963 return DestSlot;
1964}
1965
1966} // end anonymous llvm
1967
1968namespace llvm {
1969
1970void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1971 o << "#include <llvm/Module.h>\n";
1972 o << "#include <llvm/DerivedTypes.h>\n";
1973 o << "#include <llvm/Constants.h>\n";
1974 o << "#include <llvm/GlobalVariable.h>\n";
1975 o << "#include <llvm/Function.h>\n";
1976 o << "#include <llvm/CallingConv.h>\n";
1977 o << "#include <llvm/BasicBlock.h>\n";
1978 o << "#include <llvm/Instructions.h>\n";
1979 o << "#include <llvm/Pass.h>\n";
1980 o << "#include <llvm/PassManager.h>\n";
1981 o << "#include <llvm/Analysis/Verifier.h>\n";
1982 o << "#include <llvm/Assembly/PrintModulePass.h>\n";
1983 o << "#include <algorithm>\n";
1984 o << "#include <iostream>\n\n";
1985 o << "using namespace llvm;\n\n";
1986 o << "Module* makeLLVMModule();\n\n";
1987 o << "int main(int argc, char**argv) {\n";
1988 o << " Module* Mod = makeLLVMModule();\n";
1989 o << " verifyModule(*Mod, PrintMessageAction);\n";
1990 o << " PassManager PM;\n";
1991 o << " PM.add(new PrintModulePass(&std::cout));\n";
1992 o << " PM.run(*Mod);\n";
1993 o << " return 0;\n";
1994 o << "}\n\n";
1995 o << "Module* makeLLVMModule() {\n";
1996 SlotMachine SlotTable(mod);
1997 CppWriter W(o, SlotTable, mod);
1998 W.write(mod);
Reid Spencer74e032a2006-05-29 02:58:15 +00001999 o << "return mod;\n";
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00002000 o << "}\n";
2001}
2002
2003}