1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
3 // This library converts LLVM code to C code, compilable by GCC.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Assembly/CWriter.h"
8 #include "llvm/Constants.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/Module.h"
11 #include "llvm/Instructions.h"
12 #include "llvm/Pass.h"
13 #include "llvm/SymbolTable.h"
14 #include "llvm/Intrinsics.h"
15 #include "llvm/SlotCalculator.h"
16 #include "llvm/Analysis/FindUsedTypes.h"
17 #include "llvm/Analysis/ConstantsScanner.h"
18 #include "llvm/Support/InstVisitor.h"
19 #include "llvm/Support/InstIterator.h"
20 #include "Support/StringExtras.h"
21 #include "Support/STLExtras.h"
27 class CWriter : public Pass, public InstVisitor<CWriter> {
29 SlotCalculator *Table;
30 const Module *TheModule;
31 std::map<const Type *, std::string> TypeNames;
32 std::set<const Value*> MangledGlobals;
35 std::map<const ConstantFP *, unsigned> FPConstantMap;
37 CWriter(std::ostream &o) : Out(o) {}
39 void getAnalysisUsage(AnalysisUsage &AU) const {
41 AU.addRequired<FindUsedTypes>();
44 virtual bool run(Module &M) {
46 Table = new SlotCalculator(&M, false);
49 // Ensure that all structure types have names...
50 bool Changed = nameAllUsedStructureTypes(M);
58 MangledGlobals.clear();
62 std::ostream &printType(std::ostream &Out, const Type *Ty,
63 const std::string &VariableName = "",
64 bool IgnoreName = false, bool namedContext = true);
66 void writeOperand(Value *Operand);
67 void writeOperandInternal(Value *Operand);
69 std::string getValueName(const Value *V);
72 bool nameAllUsedStructureTypes(Module &M);
73 void printModule(Module *M);
74 void printSymbolTable(const SymbolTable &ST);
75 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
76 void printFunctionSignature(const Function *F, bool Prototype);
78 void printFunction(Function *);
80 void printConstant(Constant *CPV);
81 void printConstantArray(ConstantArray *CPA);
83 // isInlinableInst - Attempt to inline instructions into their uses to build
84 // trees as much as possible. To do this, we have to consistently decide
85 // what is acceptable to inline, so that variable declarations don't get
86 // printed and an extra copy of the expr is not emitted.
88 static bool isInlinableInst(const Instruction &I) {
89 // Must be an expression, must be used exactly once. If it is dead, we
90 // emit it inline where it would go.
91 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
92 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
93 isa<LoadInst>(I)) // Don't inline a load across a store!
96 // Only inline instruction it it's use is in the same BB as the inst.
97 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
100 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
101 // variables which are accessed with the & operator. This causes GCC to
102 // generate significantly better code than to emit alloca calls directly.
104 static const AllocaInst *isDirectAlloca(const Value *V) {
105 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
106 if (!AI) return false;
107 if (AI->isArrayAllocation())
108 return 0; // FIXME: we can also inline fixed size array allocas!
109 if (AI->getParent() != &AI->getParent()->getParent()->getEntryNode())
114 // Instruction visitation functions
115 friend class InstVisitor<CWriter>;
117 void visitReturnInst(ReturnInst &I);
118 void visitBranchInst(BranchInst &I);
119 void visitSwitchInst(SwitchInst &I);
121 void visitPHINode(PHINode &I);
122 void visitBinaryOperator(Instruction &I);
124 void visitCastInst (CastInst &I);
125 void visitCallInst (CallInst &I);
126 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
128 void visitMallocInst(MallocInst &I);
129 void visitAllocaInst(AllocaInst &I);
130 void visitFreeInst (FreeInst &I);
131 void visitLoadInst (LoadInst &I);
132 void visitStoreInst (StoreInst &I);
133 void visitGetElementPtrInst(GetElementPtrInst &I);
134 void visitVarArgInst(VarArgInst &I);
136 void visitInstruction(Instruction &I) {
137 std::cerr << "C Writer does not know about " << I;
141 void outputLValue(Instruction *I) {
142 Out << " " << getValueName(I) << " = ";
144 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
146 void printIndexingExpression(Value *Ptr, User::op_iterator I,
147 User::op_iterator E);
151 // We dont want identifier names with ., space, - in them.
152 // So we replace them with _
153 static std::string makeNameProper(std::string x) {
155 for (std::string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
157 case '.': tmp += "d_"; break;
158 case ' ': tmp += "s_"; break;
159 case '-': tmp += "D_"; break;
166 std::string CWriter::getValueName(const Value *V) {
167 if (V->hasName()) { // Print out the label if it exists...
168 if (isa<GlobalValue>(V) && // Do not mangle globals...
169 (cast<GlobalValue>(V)->hasExternalLinkage() &&// Unless it's internal or
170 !MangledGlobals.count(V))) // Unless the name would collide if we don't
171 return makeNameProper(V->getName());
173 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
174 makeNameProper(V->getName());
177 int Slot = Table->getValSlot(V);
178 assert(Slot >= 0 && "Invalid value!");
179 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
182 // A pointer type should not use parens around *'s alone, e.g., (**)
183 inline bool ptrTypeNameNeedsParens(const std::string &NameSoFar) {
184 return (NameSoFar.find_last_not_of('*') != std::string::npos);
187 // Pass the Type* and the variable name and this prints out the variable
190 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
191 const std::string &NameSoFar,
192 bool IgnoreName, bool namedContext) {
193 if (Ty->isPrimitiveType())
194 switch (Ty->getPrimitiveID()) {
195 case Type::VoidTyID: return Out << "void " << NameSoFar;
196 case Type::BoolTyID: return Out << "bool " << NameSoFar;
197 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
198 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
199 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
200 case Type::ShortTyID: return Out << "short " << NameSoFar;
201 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
202 case Type::IntTyID: return Out << "int " << NameSoFar;
203 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
204 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
205 case Type::FloatTyID: return Out << "float " << NameSoFar;
206 case Type::DoubleTyID: return Out << "double " << NameSoFar;
208 std::cerr << "Unknown primitive type: " << Ty << "\n";
212 // Check to see if the type is named.
213 if (!IgnoreName || isa<OpaqueType>(Ty)) {
214 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
215 if (I != TypeNames.end()) {
216 return Out << I->second << " " << NameSoFar;
220 switch (Ty->getPrimitiveID()) {
221 case Type::FunctionTyID: {
222 const FunctionType *MTy = cast<FunctionType>(Ty);
223 std::stringstream FunctionInards;
224 FunctionInards << " (" << NameSoFar << ") (";
225 for (FunctionType::ParamTypes::const_iterator
226 I = MTy->getParamTypes().begin(),
227 E = MTy->getParamTypes().end(); I != E; ++I) {
228 if (I != MTy->getParamTypes().begin())
229 FunctionInards << ", ";
230 printType(FunctionInards, *I, "");
232 if (MTy->isVarArg()) {
233 if (!MTy->getParamTypes().empty())
234 FunctionInards << ", ...";
235 } else if (MTy->getParamTypes().empty()) {
236 FunctionInards << "void";
238 FunctionInards << ")";
239 std::string tstr = FunctionInards.str();
240 printType(Out, MTy->getReturnType(), tstr);
243 case Type::StructTyID: {
244 const StructType *STy = cast<StructType>(Ty);
245 Out << NameSoFar + " {\n";
247 for (StructType::ElementTypes::const_iterator
248 I = STy->getElementTypes().begin(),
249 E = STy->getElementTypes().end(); I != E; ++I) {
251 printType(Out, *I, "field" + utostr(Idx++));
257 case Type::PointerTyID: {
258 const PointerType *PTy = cast<PointerType>(Ty);
259 std::string ptrName = "*" + NameSoFar;
261 // Do not need parens around "* NameSoFar" if NameSoFar consists only
262 // of zero or more '*' chars *and* this is not an unnamed pointer type
263 // such as the result type in a cast statement. Otherwise, enclose in ( ).
264 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
265 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
266 ptrName = "(" + ptrName + ")"; //
268 return printType(Out, PTy->getElementType(), ptrName);
271 case Type::ArrayTyID: {
272 const ArrayType *ATy = cast<ArrayType>(Ty);
273 unsigned NumElements = ATy->getNumElements();
274 return printType(Out, ATy->getElementType(),
275 NameSoFar + "[" + utostr(NumElements) + "]");
278 case Type::OpaqueTyID: {
279 static int Count = 0;
280 std::string TyName = "struct opaque_" + itostr(Count++);
281 assert(TypeNames.find(Ty) == TypeNames.end());
282 TypeNames[Ty] = TyName;
283 return Out << TyName << " " << NameSoFar;
286 assert(0 && "Unhandled case in getTypeProps!");
293 void CWriter::printConstantArray(ConstantArray *CPA) {
295 // As a special case, print the array as a string if it is an array of
296 // ubytes or an array of sbytes with positive values.
298 const Type *ETy = CPA->getType()->getElementType();
299 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
301 // Make sure the last character is a null char, as automatically added by C
302 if (isString && (CPA->getNumOperands() == 0 ||
303 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
308 // Keep track of whether the last number was a hexadecimal escape
309 bool LastWasHex = false;
311 // Do not include the last character, which we know is null
312 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
313 unsigned char C = (ETy == Type::SByteTy) ?
314 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
315 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
317 // Print it out literally if it is a printable character. The only thing
318 // to be careful about is when the last letter output was a hex escape
319 // code, in which case we have to be careful not to print out hex digits
320 // explicitly (the C compiler thinks it is a continuation of the previous
321 // character, sheesh...)
323 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
325 if (C == '"' || C == '\\')
332 case '\n': Out << "\\n"; break;
333 case '\t': Out << "\\t"; break;
334 case '\r': Out << "\\r"; break;
335 case '\v': Out << "\\v"; break;
336 case '\a': Out << "\\a"; break;
337 case '\"': Out << "\\\""; break;
338 case '\'': Out << "\\\'"; break;
341 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
342 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
351 if (CPA->getNumOperands()) {
353 printConstant(cast<Constant>(CPA->getOperand(0)));
354 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
356 printConstant(cast<Constant>(CPA->getOperand(i)));
363 /// FPCSafeToPrint - Returns true if we may assume that CFP may be
364 /// written out textually as a double (rather than as a reference to a
365 /// stack-allocated variable). We decide this by converting CFP to a
366 /// string and back into a double, and then checking whether the
367 /// conversion results in a bit-equal double to the original value of
368 /// CFP. This depends on us and the target C compiler agreeing on the
369 /// conversion process (which is pretty likely since we only deal in
370 /// IEEE FP.) This is adapted from similar code in
371 /// lib/VMCore/AsmWriter.cpp:WriteConstantInt().
372 static bool FPCSafeToPrint (const ConstantFP *CFP) {
373 std::string StrVal = ftostr(CFP->getValue());
374 // Check to make sure that the stringized number is not some string like
375 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
376 // the string matches the "[-+]?[0-9]" regex.
377 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
378 ((StrVal[0] == '-' || StrVal[0] == '+') &&
379 (StrVal[1] >= '0' && StrVal[1] <= '9')))
380 // Reparse stringized version!
381 return (atof(StrVal.c_str()) == CFP->getValue());
385 // printConstant - The LLVM Constant to C Constant converter.
386 void CWriter::printConstant(Constant *CPV) {
387 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
388 switch (CE->getOpcode()) {
389 case Instruction::Cast:
391 printType(Out, CPV->getType());
393 printConstant(CE->getOperand(0));
397 case Instruction::GetElementPtr:
399 printIndexingExpression(CE->getOperand(0),
400 CPV->op_begin()+1, CPV->op_end());
403 case Instruction::Add:
405 printConstant(CE->getOperand(0));
407 printConstant(CE->getOperand(1));
410 case Instruction::Sub:
412 printConstant(CE->getOperand(0));
414 printConstant(CE->getOperand(1));
419 std::cerr << "CWriter Error: Unhandled constant expression: "
425 switch (CPV->getType()->getPrimitiveID()) {
427 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
428 case Type::SByteTyID:
429 case Type::ShortTyID:
430 Out << cast<ConstantSInt>(CPV)->getValue(); break;
432 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
433 Out << "((int)0x80000000)"; // Handle MININT specially to avoid warning
435 Out << cast<ConstantSInt>(CPV)->getValue();
439 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
441 case Type::UByteTyID:
442 case Type::UShortTyID:
443 Out << cast<ConstantUInt>(CPV)->getValue(); break;
445 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
446 case Type::ULongTyID:
447 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
449 case Type::FloatTyID:
450 case Type::DoubleTyID: {
451 ConstantFP *FPC = cast<ConstantFP>(CPV);
452 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
453 if (I != FPConstantMap.end()) {
454 // Because of FP precision problems we must load from a stack allocated
455 // value that holds the value in hex.
456 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
457 << "*)&FloatConstant" << I->second << ")";
459 if (FPCSafeToPrint (FPC)) {
460 Out << ftostr (FPC->getValue ());
462 Out << FPC->getValue(); // Who knows? Give it our best shot...
468 case Type::ArrayTyID:
469 printConstantArray(cast<ConstantArray>(CPV));
472 case Type::StructTyID: {
474 if (CPV->getNumOperands()) {
476 printConstant(cast<Constant>(CPV->getOperand(0)));
477 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
479 printConstant(cast<Constant>(CPV->getOperand(i)));
486 case Type::PointerTyID:
487 if (isa<ConstantPointerNull>(CPV)) {
489 printType(Out, CPV->getType());
490 Out << ")/*NULL*/0)";
492 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
493 writeOperand(CPR->getValue());
498 std::cerr << "Unknown constant type: " << CPV << "\n";
503 void CWriter::writeOperandInternal(Value *Operand) {
504 if (Instruction *I = dyn_cast<Instruction>(Operand))
505 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
506 // Should we inline this instruction to build a tree?
513 if (Operand->hasName()) {
514 Out << getValueName(Operand);
515 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
518 int Slot = Table->getValSlot(Operand);
519 assert(Slot >= 0 && "Malformed LLVM!");
520 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
524 void CWriter::writeOperand(Value *Operand) {
525 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
526 Out << "(&"; // Global variables are references as their addresses by llvm
528 writeOperandInternal(Operand);
530 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
534 // nameAllUsedStructureTypes - If there are structure types in the module that
535 // are used but do not have names assigned to them in the symbol table yet then
536 // we assign them names now.
538 bool CWriter::nameAllUsedStructureTypes(Module &M) {
539 // Get a set of types that are used by the program...
540 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
542 // Loop over the module symbol table, removing types from UT that are already
545 SymbolTable &MST = M.getSymbolTable();
546 if (MST.find(Type::TypeTy) != MST.end())
547 for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
548 E = MST.type_end(Type::TypeTy); I != E; ++I)
549 UT.erase(cast<Type>(I->second));
551 // UT now contains types that are not named. Loop over it, naming structure
554 bool Changed = false;
555 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
557 if (const StructType *ST = dyn_cast<StructType>(*I)) {
558 ((Value*)ST)->setName("unnamed", &MST);
564 static void generateAllocaDecl(std::ostream& Out) {
565 // On SunOS, we need to insert the alloca macro & proto for the builtin.
566 Out << "#ifdef sun\n"
567 << "extern void *__builtin_alloca(unsigned long);\n"
568 << "#define alloca(x) __builtin_alloca(x)\n"
570 << "#ifndef __FreeBSD__\n"
571 << "#include <alloca.h>\n"
576 void CWriter::printModule(Module *M) {
577 // Calculate which global values have names that will collide when we throw
578 // away type information.
579 { // Scope to delete the FoundNames set when we are done with it...
580 std::set<std::string> FoundNames;
581 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
582 if (I->hasName()) // If the global has a name...
583 if (FoundNames.count(I->getName())) // And the name is already used
584 MangledGlobals.insert(I); // Mangle the name
586 FoundNames.insert(I->getName()); // Otherwise, keep track of name
588 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
589 if (I->hasName()) // If the global has a name...
590 if (FoundNames.count(I->getName())) // And the name is already used
591 MangledGlobals.insert(I); // Mangle the name
593 FoundNames.insert(I->getName()); // Otherwise, keep track of name
596 // get declaration for alloca
597 Out << "/* Provide Declarations */\n";
598 generateAllocaDecl(Out);
599 Out << "#include <stdarg.h>\n";
600 Out << "#include <setjmp.h>\n";
602 // Provide a definition for `bool' if not compiling with a C++ compiler.
604 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
606 << "\n\n/* Support for floating point constants */\n"
607 << "typedef unsigned long long ConstantDoubleTy;\n"
608 << "typedef unsigned int ConstantFloatTy;\n"
610 << "\n\n/* Global Declarations */\n";
612 // First output all the declarations for the program, because C requires
613 // Functions & globals to be declared before they are used.
616 // Loop over the symbol table, emitting all named constants...
617 printSymbolTable(M->getSymbolTable());
619 // Global variable declarations...
621 Out << "\n/* External Global Variable Declarations */\n";
622 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
623 if (I->hasExternalLinkage()) {
625 printType(Out, I->getType()->getElementType(), getValueName(I));
631 // Function declarations
633 Out << "\n/* Function Declarations */\n";
635 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
636 // If the function is external and the name collides don't print it.
637 // Sometimes the bytecode likes to have multiple "declarations" for
638 // external functions
639 if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
640 !I->getIntrinsicID()) {
641 printFunctionSignature(I, true);
647 // Print Malloc prototype if needed
649 Out << "\n/* Malloc to make sun happy */\n";
650 Out << "extern void * malloc(size_t);\n\n";
653 // Output the global variable declerations
655 Out << "\n\n/* Global Variable Declerations */\n";
656 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
657 if (!I->isExternal()) {
659 printType(Out, I->getType()->getElementType(), getValueName(I));
666 // Output the global variable definitions and contents...
668 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
669 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
670 if (!I->isExternal()) {
671 if (I->hasInternalLinkage())
673 printType(Out, I->getType()->getElementType(), getValueName(I));
674 if (!I->getInitializer()->isNullValue()) {
676 writeOperand(I->getInitializer());
682 // Output all of the functions...
684 Out << "\n\n/* Function Bodies */\n";
685 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
691 /// printSymbolTable - Run through symbol table looking for type names. If a
692 /// type name is found, emit it's declaration...
694 void CWriter::printSymbolTable(const SymbolTable &ST) {
695 // If there are no type names, exit early.
696 if (ST.find(Type::TypeTy) == ST.end())
699 // We are only interested in the type plane of the symbol table...
700 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
701 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
703 // Print out forward declarations for structure types before anything else!
704 Out << "/* Structure forward decls */\n";
705 for (; I != End; ++I)
706 if (const Type *STy = dyn_cast<StructType>(I->second)) {
707 std::string Name = "struct l_" + makeNameProper(I->first);
708 Out << Name << ";\n";
709 TypeNames.insert(std::make_pair(STy, Name));
714 // Now we can print out typedefs...
715 Out << "/* Typedefs */\n";
716 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
717 const Type *Ty = cast<Type>(I->second);
718 std::string Name = "l_" + makeNameProper(I->first);
720 printType(Out, Ty, Name);
726 // Keep track of which structures have been printed so far...
727 std::set<const StructType *> StructPrinted;
729 // Loop over all structures then push them into the stack so they are
730 // printed in the correct order.
732 Out << "/* Structure contents */\n";
733 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
734 if (const StructType *STy = dyn_cast<StructType>(I->second))
735 printContainedStructs(STy, StructPrinted);
738 // Push the struct onto the stack and recursively push all structs
739 // this one depends on.
740 void CWriter::printContainedStructs(const Type *Ty,
741 std::set<const StructType*> &StructPrinted){
742 if (const StructType *STy = dyn_cast<StructType>(Ty)){
743 //Check to see if we have already printed this struct
744 if (StructPrinted.count(STy) == 0) {
745 // Print all contained types first...
746 for (StructType::ElementTypes::const_iterator
747 I = STy->getElementTypes().begin(),
748 E = STy->getElementTypes().end(); I != E; ++I) {
749 const Type *Ty1 = I->get();
750 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
751 printContainedStructs(*I, StructPrinted);
754 //Print structure type out..
755 StructPrinted.insert(STy);
756 std::string Name = TypeNames[STy];
757 printType(Out, STy, Name, true);
761 // If it is an array, check contained types and continue
762 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
763 const Type *Ty1 = ATy->getElementType();
764 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
765 printContainedStructs(Ty1, StructPrinted);
770 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
771 // If the program provides it's own malloc prototype we don't need
772 // to include the general one.
773 if (getValueName(F) == "malloc")
775 if (F->hasInternalLinkage()) Out << "static ";
776 // Loop over the arguments, printing them...
777 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
779 std::stringstream FunctionInards;
781 // Print out the name...
782 FunctionInards << getValueName(F) << "(";
784 if (!F->isExternal()) {
787 if (F->abegin()->hasName() || !Prototype)
788 ArgName = getValueName(F->abegin());
789 printType(FunctionInards, F->afront().getType(), ArgName);
790 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
792 FunctionInards << ", ";
793 if (I->hasName() || !Prototype)
794 ArgName = getValueName(I);
797 printType(FunctionInards, I->getType(), ArgName);
801 // Loop over the arguments, printing them...
802 for (FunctionType::ParamTypes::const_iterator I =
803 FT->getParamTypes().begin(),
804 E = FT->getParamTypes().end(); I != E; ++I) {
805 if (I != FT->getParamTypes().begin()) FunctionInards << ", ";
806 printType(FunctionInards, *I);
810 // Finish printing arguments... if this is a vararg function, print the ...,
811 // unless there are no known types, in which case, we just emit ().
813 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
814 if (FT->getParamTypes().size()) FunctionInards << ", ";
815 FunctionInards << "..."; // Output varargs portion of signature!
817 FunctionInards << ")";
818 // Print out the return type and the entire signature for that matter
819 printType(Out, F->getReturnType(), FunctionInards.str());
823 void CWriter::printFunction(Function *F) {
824 if (F->isExternal()) return;
826 Table->incorporateFunction(F);
828 printFunctionSignature(F, false);
831 // print local variable information for the function
832 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
833 if (const AllocaInst *AI = isDirectAlloca(*I)) {
835 printType(Out, AI->getAllocatedType(), getValueName(AI));
836 Out << "; /* Address exposed local */\n";
837 } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
839 printType(Out, (*I)->getType(), getValueName(*I));
842 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
844 printType(Out, (*I)->getType(), getValueName(*I)+"__PHI_TEMPORARY");
851 // Scan the function for floating point constants. If any FP constant is used
852 // in the function, we want to redirect it here so that we do not depend on
853 // the precision of the printed form, unless the printed form preserves
856 unsigned FPCounter = 0;
857 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
858 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
859 if ((!FPCSafeToPrint(FPC)) // Do not put in FPConstantMap if safe.
860 && (FPConstantMap.find(FPC) == FPConstantMap.end())) {
861 double Val = FPC->getValue();
863 FPConstantMap[FPC] = FPCounter; // Number the FP constants
865 if (FPC->getType() == Type::DoubleTy)
866 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
867 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
868 << "; /* " << Val << " */\n";
869 else if (FPC->getType() == Type::FloatTy) {
871 Out << " const ConstantFloatTy FloatConstant" << FPCounter++
872 << " = 0x" << std::hex << *(unsigned*)&fVal << std::dec
873 << "; /* " << Val << " */\n";
875 assert(0 && "Unknown float type!");
880 // print the basic blocks
881 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
882 BasicBlock *Prev = BB->getPrev();
884 // Don't print the label for the basic block if there are no uses, or if the
885 // only terminator use is the precessor basic block's terminator. We have
886 // to scan the use list because PHI nodes use basic blocks too but do not
887 // require a label to be generated.
889 bool NeedsLabel = false;
890 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
892 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
893 if (TI != Prev->getTerminator() ||
894 isa<SwitchInst>(Prev->getTerminator())) {
899 if (NeedsLabel) Out << getValueName(BB) << ":\n";
901 // Output all of the instructions in the basic block...
902 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
903 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
904 if (II->getType() != Type::VoidTy)
913 // Don't emit prefix or suffix for the terminator...
914 visit(*BB->getTerminator());
918 Table->purgeFunction();
919 FPConstantMap.clear();
922 // Specific Instruction type classes... note that all of the casts are
923 // neccesary because we use the instruction classes as opaque types...
925 void CWriter::visitReturnInst(ReturnInst &I) {
926 // Don't output a void return if this is the last basic block in the function
927 if (I.getNumOperands() == 0 &&
928 &*--I.getParent()->getParent()->end() == I.getParent() &&
929 !I.getParent()->size() == 1) {
934 if (I.getNumOperands()) {
936 writeOperand(I.getOperand(0));
941 void CWriter::visitSwitchInst(SwitchInst &SI) {
943 writeOperand(SI.getOperand(0));
944 Out << ") {\n default:\n";
945 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
947 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
949 writeOperand(SI.getOperand(i));
951 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
952 printBranchToBlock(SI.getParent(), Succ, 2);
953 if (Succ == SI.getParent()->getNext())
960 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
961 // If PHI nodes need copies, we need the copy code...
962 if (isa<PHINode>(To->front()) ||
963 From->getNext() != To) // Not directly successor, need goto
966 // Otherwise we don't need the code.
970 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
972 for (BasicBlock::iterator I = Succ->begin();
973 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
974 // now we have to do the printing
975 Out << std::string(Indent, ' ');
976 Out << " " << getValueName(I) << "__PHI_TEMPORARY = ";
977 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
978 Out << "; /* for PHI node */\n";
981 if (CurBB->getNext() != Succ) {
982 Out << std::string(Indent, ' ') << " goto ";
988 // Brach instruction printing - Avoid printing out a brach to a basic block that
989 // immediately succeeds the current one.
991 void CWriter::visitBranchInst(BranchInst &I) {
992 if (I.isConditional()) {
993 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
995 writeOperand(I.getCondition());
998 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1000 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
1001 Out << " } else {\n";
1002 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1005 // First goto not neccesary, assume second one is...
1007 writeOperand(I.getCondition());
1010 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1015 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1020 // PHI nodes get copied into temporary values at the end of predecessor basic
1021 // blocks. We now need to copy these temporary values into the REAL value for
1023 void CWriter::visitPHINode(PHINode &I) {
1025 Out << "__PHI_TEMPORARY";
1029 void CWriter::visitBinaryOperator(Instruction &I) {
1030 // binary instructions, shift instructions, setCond instructions.
1031 assert(!isa<PointerType>(I.getType()));
1033 // We must cast the results of binary operations which might be promoted.
1034 bool needsCast = false;
1035 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1036 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)) {
1039 printType(Out, I.getType(), "", false, false);
1043 writeOperand(I.getOperand(0));
1045 switch (I.getOpcode()) {
1046 case Instruction::Add: Out << " + "; break;
1047 case Instruction::Sub: Out << " - "; break;
1048 case Instruction::Mul: Out << "*"; break;
1049 case Instruction::Div: Out << "/"; break;
1050 case Instruction::Rem: Out << "%"; break;
1051 case Instruction::And: Out << " & "; break;
1052 case Instruction::Or: Out << " | "; break;
1053 case Instruction::Xor: Out << " ^ "; break;
1054 case Instruction::SetEQ: Out << " == "; break;
1055 case Instruction::SetNE: Out << " != "; break;
1056 case Instruction::SetLE: Out << " <= "; break;
1057 case Instruction::SetGE: Out << " >= "; break;
1058 case Instruction::SetLT: Out << " < "; break;
1059 case Instruction::SetGT: Out << " > "; break;
1060 case Instruction::Shl : Out << " << "; break;
1061 case Instruction::Shr : Out << " >> "; break;
1062 default: std::cerr << "Invalid operator type!" << I; abort();
1065 writeOperand(I.getOperand(1));
1072 void CWriter::visitCastInst(CastInst &I) {
1073 if (I.getType() == Type::BoolTy) {
1075 writeOperand(I.getOperand(0));
1080 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1082 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1083 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1084 // Avoid "cast to pointer from integer of different size" warnings
1088 writeOperand(I.getOperand(0));
1091 void CWriter::visitCallInst(CallInst &I) {
1092 // Handle intrinsic function calls first...
1093 if (Function *F = I.getCalledFunction())
1094 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1096 default: assert(0 && "Unknown LLVM intrinsic!");
1097 case LLVMIntrinsic::va_start:
1098 Out << "va_start((va_list)*";
1099 writeOperand(I.getOperand(1));
1101 // Output the last argument to the enclosing function...
1102 writeOperand(&I.getParent()->getParent()->aback());
1105 case LLVMIntrinsic::va_end:
1106 Out << "va_end((va_list)*";
1107 writeOperand(I.getOperand(1));
1110 case LLVMIntrinsic::va_copy:
1111 Out << "va_copy((va_list)*";
1112 writeOperand(I.getOperand(1));
1113 Out << ", (va_list)";
1114 writeOperand(I.getOperand(2));
1118 case LLVMIntrinsic::setjmp:
1119 Out << "setjmp((jmp_buf)";
1120 writeOperand(I.getOperand(1));
1123 case LLVMIntrinsic::longjmp:
1124 Out << "longjmp((jmp_buf)";
1125 writeOperand(I.getOperand(1));
1127 writeOperand(I.getOperand(2));
1133 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
1134 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1135 const Type *RetTy = FTy->getReturnType();
1137 writeOperand(I.getOperand(0));
1140 if (I.getNumOperands() > 1) {
1141 writeOperand(I.getOperand(1));
1143 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
1145 writeOperand(I.getOperand(op));
1151 void CWriter::visitMallocInst(MallocInst &I) {
1153 printType(Out, I.getType());
1154 Out << ")malloc(sizeof(";
1155 printType(Out, I.getType()->getElementType());
1158 if (I.isArrayAllocation()) {
1160 writeOperand(I.getOperand(0));
1165 void CWriter::visitAllocaInst(AllocaInst &I) {
1167 printType(Out, I.getType());
1168 Out << ") alloca(sizeof(";
1169 printType(Out, I.getType()->getElementType());
1171 if (I.isArrayAllocation()) {
1173 writeOperand(I.getOperand(0));
1178 void CWriter::visitFreeInst(FreeInst &I) {
1180 writeOperand(I.getOperand(0));
1184 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1185 User::op_iterator E) {
1186 bool HasImplicitAddress = false;
1187 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1188 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1189 HasImplicitAddress = true;
1190 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1191 HasImplicitAddress = true;
1192 Ptr = CPR->getValue(); // Get to the global...
1193 } else if (isDirectAlloca(Ptr)) {
1194 HasImplicitAddress = true;
1198 if (!HasImplicitAddress)
1199 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1201 writeOperandInternal(Ptr);
1205 const Constant *CI = dyn_cast<Constant>(I);
1206 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1209 writeOperandInternal(Ptr);
1211 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1213 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1216 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1217 "Can only have implicit address with direct accessing");
1219 if (HasImplicitAddress) {
1221 } else if (CI && CI->isNullValue() && I+1 != E) {
1222 // Print out the -> operator if possible...
1223 if ((*(I+1))->getType() == Type::UByteTy) {
1224 Out << (HasImplicitAddress ? "." : "->");
1225 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1231 if ((*I)->getType() == Type::LongTy) {
1236 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1240 void CWriter::visitLoadInst(LoadInst &I) {
1242 writeOperand(I.getOperand(0));
1245 void CWriter::visitStoreInst(StoreInst &I) {
1247 writeOperand(I.getPointerOperand());
1249 writeOperand(I.getOperand(0));
1252 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1254 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1257 void CWriter::visitVarArgInst(VarArgInst &I) {
1258 Out << "va_arg((va_list)*";
1259 writeOperand(I.getOperand(0));
1261 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1266 //===----------------------------------------------------------------------===//
1267 // External Interface declaration
1268 //===----------------------------------------------------------------------===//
1270 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }