1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
3 // This library converts LLVM code to C code, compilable by GCC.
5 //===-----------------------------------------------------------------------==//
6 #include "llvm/Assembly/CWriter.h"
7 #include "llvm/Constants.h"
8 #include "llvm/DerivedTypes.h"
9 #include "llvm/Module.h"
10 #include "llvm/iMemory.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iPHINode.h"
13 #include "llvm/iOther.h"
14 #include "llvm/iOperators.h"
15 #include "llvm/Pass.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/SlotCalculator.h"
18 #include "llvm/Analysis/FindUsedTypes.h"
19 #include "llvm/Analysis/ConstantsScanner.h"
20 #include "llvm/Support/InstVisitor.h"
21 #include "llvm/Support/InstIterator.h"
22 #include "Support/StringExtras.h"
23 #include "Support/STLExtras.h"
32 class CWriter : public Pass, public InstVisitor<CWriter> {
34 SlotCalculator *Table;
35 const Module *TheModule;
36 map<const Type *, string> TypeNames;
37 std::set<const Value*> MangledGlobals;
40 map<const ConstantFP *, unsigned> FPConstantMap;
42 CWriter(ostream &o) : Out(o) {}
44 void getAnalysisUsage(AnalysisUsage &AU) const {
46 AU.addRequired<FindUsedTypes>();
49 virtual bool run(Module &M) {
51 Table = new SlotCalculator(&M, false);
54 // Ensure that all structure types have names...
55 bool Changed = nameAllUsedStructureTypes(M);
63 MangledGlobals.clear();
67 ostream &printType(const Type *Ty, const string &VariableName = "",
68 bool IgnoreName = false, bool namedContext = true);
70 void writeOperand(Value *Operand);
71 void writeOperandInternal(Value *Operand);
73 string getValueName(const Value *V);
76 bool nameAllUsedStructureTypes(Module &M);
77 void printModule(Module *M);
78 void printSymbolTable(const SymbolTable &ST);
79 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
80 void printGlobal(const GlobalVariable *GV);
81 void printFunctionSignature(const Function *F, bool Prototype);
83 void printFunction(Function *);
85 void printConstant(Constant *CPV);
86 void printConstantArray(ConstantArray *CPA);
88 // isInlinableInst - Attempt to inline instructions into their uses to build
89 // trees as much as possible. To do this, we have to consistently decide
90 // what is acceptable to inline, so that variable declarations don't get
91 // printed and an extra copy of the expr is not emitted.
93 static bool isInlinableInst(const Instruction &I) {
94 // Must be an expression, must be used exactly once. If it is dead, we
95 // emit it inline where it would go.
96 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
97 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
98 isa<LoadInst>(I)) // Don't inline a load across a store!
101 // Only inline instruction it it's use is in the same BB as the inst.
102 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
105 // Instruction visitation functions
106 friend class InstVisitor<CWriter>;
108 void visitReturnInst(ReturnInst &I);
109 void visitBranchInst(BranchInst &I);
111 void visitPHINode(PHINode &I) {}
112 void visitBinaryOperator(Instruction &I);
114 void visitCastInst (CastInst &I);
115 void visitCallInst (CallInst &I);
116 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
118 void visitMallocInst(MallocInst &I);
119 void visitAllocaInst(AllocaInst &I);
120 void visitFreeInst (FreeInst &I);
121 void visitLoadInst (LoadInst &I);
122 void visitStoreInst (StoreInst &I);
123 void visitGetElementPtrInst(GetElementPtrInst &I);
125 void visitInstruction(Instruction &I) {
126 std::cerr << "C Writer does not know about " << I;
130 void outputLValue(Instruction *I) {
131 Out << " " << getValueName(I) << " = ";
133 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
135 void printIndexingExpression(Value *Ptr, User::op_iterator I,
136 User::op_iterator E);
140 // We dont want identifier names with ., space, - in them.
141 // So we replace them with _
142 static string makeNameProper(string x) {
144 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
146 case '.': tmp += "d_"; break;
147 case ' ': tmp += "s_"; break;
148 case '-': tmp += "D_"; break;
155 string CWriter::getValueName(const Value *V) {
156 if (V->hasName()) { // Print out the label if it exists...
157 if (isa<GlobalValue>(V) && // Do not mangle globals...
158 cast<GlobalValue>(V)->hasExternalLinkage() && // Unless it's internal or
159 !MangledGlobals.count(V)) // Unless the name would collide if we don't
160 return makeNameProper(V->getName());
162 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
163 makeNameProper(V->getName());
166 int Slot = Table->getValSlot(V);
167 assert(Slot >= 0 && "Invalid value!");
168 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
171 // A pointer type should not use parens around *'s alone, e.g., (**)
172 inline bool ptrTypeNameNeedsParens(const string &NameSoFar) {
173 return (NameSoFar.find_last_not_of('*') != std::string::npos);
176 // Pass the Type* and the variable name and this prints out the variable
179 ostream &CWriter::printType(const Type *Ty, const string &NameSoFar,
180 bool IgnoreName, bool namedContext) {
181 if (Ty->isPrimitiveType())
182 switch (Ty->getPrimitiveID()) {
183 case Type::VoidTyID: return Out << "void " << NameSoFar;
184 case Type::BoolTyID: return Out << "bool " << NameSoFar;
185 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
186 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
187 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
188 case Type::ShortTyID: return Out << "short " << NameSoFar;
189 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
190 case Type::IntTyID: return Out << "int " << NameSoFar;
191 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
192 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
193 case Type::FloatTyID: return Out << "float " << NameSoFar;
194 case Type::DoubleTyID: return Out << "double " << NameSoFar;
196 std::cerr << "Unknown primitive type: " << Ty << "\n";
200 // Check to see if the type is named.
201 if (!IgnoreName || isa<OpaqueType>(Ty)) {
202 map<const Type *, string>::iterator I = TypeNames.find(Ty);
203 if (I != TypeNames.end()) {
204 return Out << I->second << " " << NameSoFar;
208 switch (Ty->getPrimitiveID()) {
209 case Type::FunctionTyID: {
210 const FunctionType *MTy = cast<FunctionType>(Ty);
211 printType(MTy->getReturnType(), "");
212 Out << " (" << NameSoFar << ") (";
214 for (FunctionType::ParamTypes::const_iterator
215 I = MTy->getParamTypes().begin(),
216 E = MTy->getParamTypes().end(); I != E; ++I) {
217 if (I != MTy->getParamTypes().begin())
221 if (MTy->isVarArg()) {
222 if (!MTy->getParamTypes().empty())
228 case Type::StructTyID: {
229 const StructType *STy = cast<StructType>(Ty);
230 Out << NameSoFar + " {\n";
232 for (StructType::ElementTypes::const_iterator
233 I = STy->getElementTypes().begin(),
234 E = STy->getElementTypes().end(); I != E; ++I) {
236 printType(*I, "field" + utostr(Idx++));
242 case Type::PointerTyID: {
243 const PointerType *PTy = cast<PointerType>(Ty);
244 std::string ptrName = "*" + NameSoFar;
246 // Do not need parens around "* NameSoFar" if NameSoFar consists only
247 // of zero or more '*' chars *and* this is not an unnamed pointer type
248 // such as the result type in a cast statement. Otherwise, enclose in ( ).
249 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
250 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
251 ptrName = "(" + ptrName + ")"; //
253 return printType(PTy->getElementType(), ptrName);
256 case Type::ArrayTyID: {
257 const ArrayType *ATy = cast<ArrayType>(Ty);
258 unsigned NumElements = ATy->getNumElements();
259 return printType(ATy->getElementType(),
260 NameSoFar + "[" + utostr(NumElements) + "]");
263 case Type::OpaqueTyID: {
264 static int Count = 0;
265 string TyName = "struct opaque_" + itostr(Count++);
266 assert(TypeNames.find(Ty) == TypeNames.end());
267 TypeNames[Ty] = TyName;
268 return Out << TyName << " " << NameSoFar;
271 assert(0 && "Unhandled case in getTypeProps!");
278 void CWriter::printConstantArray(ConstantArray *CPA) {
280 // As a special case, print the array as a string if it is an array of
281 // ubytes or an array of sbytes with positive values.
283 const Type *ETy = CPA->getType()->getElementType();
284 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
286 // Make sure the last character is a null char, as automatically added by C
287 if (CPA->getNumOperands() == 0 ||
288 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
293 // Do not include the last character, which we know is null
294 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
295 unsigned char C = (ETy == Type::SByteTy) ?
296 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
297 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
300 if (C == '"' || C == '\\')
306 case '\n': Out << "\\n"; break;
307 case '\t': Out << "\\t"; break;
308 case '\r': Out << "\\r"; break;
309 case '\v': Out << "\\v"; break;
310 case '\a': Out << "\\a"; break;
311 case '\"': Out << "\\\""; break;
312 case '\'': Out << "\\\'"; break;
315 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
316 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
324 if (CPA->getNumOperands()) {
326 printConstant(cast<Constant>(CPA->getOperand(0)));
327 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
329 printConstant(cast<Constant>(CPA->getOperand(i)));
337 // printConstant - The LLVM Constant to C Constant converter.
338 void CWriter::printConstant(Constant *CPV) {
339 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
340 switch (CE->getOpcode()) {
341 case Instruction::Cast:
343 printType(CPV->getType());
345 printConstant(cast<Constant>(CPV->getOperand(0)));
349 case Instruction::GetElementPtr:
351 printIndexingExpression(CPV->getOperand(0),
352 CPV->op_begin()+1, CPV->op_end());
355 case Instruction::Add:
357 printConstant(cast<Constant>(CPV->getOperand(0)));
359 printConstant(cast<Constant>(CPV->getOperand(1)));
362 case Instruction::Sub:
364 printConstant(cast<Constant>(CPV->getOperand(0)));
366 printConstant(cast<Constant>(CPV->getOperand(1)));
371 std::cerr << "CWriter Error: Unhandled constant expression: "
377 switch (CPV->getType()->getPrimitiveID()) {
379 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
380 case Type::SByteTyID:
381 case Type::ShortTyID:
383 Out << cast<ConstantSInt>(CPV)->getValue(); break;
385 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
387 case Type::UByteTyID:
388 case Type::UShortTyID:
389 Out << cast<ConstantUInt>(CPV)->getValue(); break;
391 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
392 case Type::ULongTyID:
393 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
395 case Type::FloatTyID:
396 case Type::DoubleTyID: {
397 ConstantFP *FPC = cast<ConstantFP>(CPV);
398 map<const ConstantFP *, unsigned>::iterator I = FPConstantMap.find(FPC);
399 if (I != FPConstantMap.end()) {
400 // Because of FP precision problems we must load from a stack allocated
401 // value that holds the value in hex.
402 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
403 << "*)&FloatConstant" << I->second << ")";
405 Out << FPC->getValue();
410 case Type::ArrayTyID:
411 printConstantArray(cast<ConstantArray>(CPV));
414 case Type::StructTyID: {
416 if (CPV->getNumOperands()) {
418 printConstant(cast<Constant>(CPV->getOperand(0)));
419 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
421 printConstant(cast<Constant>(CPV->getOperand(i)));
428 case Type::PointerTyID:
429 if (isa<ConstantPointerNull>(CPV)) {
432 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
433 writeOperand(CPR->getValue());
438 std::cerr << "Unknown constant type: " << CPV << "\n";
443 void CWriter::writeOperandInternal(Value *Operand) {
444 if (Instruction *I = dyn_cast<Instruction>(Operand))
445 if (isInlinableInst(*I)) {
446 // Should we inline this instruction to build a tree?
453 if (Operand->hasName()) {
454 Out << getValueName(Operand);
455 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
458 int Slot = Table->getValSlot(Operand);
459 assert(Slot >= 0 && "Malformed LLVM!");
460 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
464 void CWriter::writeOperand(Value *Operand) {
465 if (isa<GlobalVariable>(Operand))
466 Out << "(&"; // Global variables are references as their addresses by llvm
468 writeOperandInternal(Operand);
470 if (isa<GlobalVariable>(Operand))
474 // nameAllUsedStructureTypes - If there are structure types in the module that
475 // are used but do not have names assigned to them in the symbol table yet then
476 // we assign them names now.
478 bool CWriter::nameAllUsedStructureTypes(Module &M) {
479 // Get a set of types that are used by the program...
480 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
482 // Loop over the module symbol table, removing types from UT that are already
485 SymbolTable *MST = M.getSymbolTableSure();
486 if (MST->find(Type::TypeTy) != MST->end())
487 for (SymbolTable::type_iterator I = MST->type_begin(Type::TypeTy),
488 E = MST->type_end(Type::TypeTy); I != E; ++I)
489 UT.erase(cast<Type>(I->second));
491 // UT now contains types that are not named. Loop over it, naming structure
494 bool Changed = false;
495 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
497 if (const StructType *ST = dyn_cast<StructType>(*I)) {
498 ((Value*)ST)->setName("unnamed", MST);
504 void CWriter::printModule(Module *M) {
505 // Calculate which global values have names that will collide when we throw
506 // away type information.
507 { // Scope to delete the FoundNames set when we are done with it...
508 std::set<string> FoundNames;
509 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
510 if (I->hasName()) // If the global has a name...
511 if (FoundNames.count(I->getName())) // And the name is already used
512 MangledGlobals.insert(I); // Mangle the name
514 FoundNames.insert(I->getName()); // Otherwise, keep track of name
516 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
517 if (I->hasName()) // If the global has a name...
518 if (FoundNames.count(I->getName())) // And the name is already used
519 MangledGlobals.insert(I); // Mangle the name
521 FoundNames.insert(I->getName()); // Otherwise, keep track of name
524 // printing stdlib inclusion
525 //Out << "#include <stdlib.h>\n";
527 // get declaration for alloca
528 Out << "/* Provide Declarations */\n"
529 << "#include <alloca.h>\n\n"
531 // Provide a definition for null if one does not already exist,
532 // and for `bool' if not compiling with a C++ compiler.
533 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
534 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
536 << "\n\n/* Support for floating point constants */\n"
537 << "typedef unsigned long long ConstantDoubleTy;\n"
538 << "typedef unsigned int ConstantFloatTy;\n"
540 << "\n\n/* Global Declarations */\n";
542 // First output all the declarations for the program, because C requires
543 // Functions & globals to be declared before they are used.
546 // Loop over the symbol table, emitting all named constants...
547 if (M->hasSymbolTable())
548 printSymbolTable(*M->getSymbolTable());
550 // Global variable declarations...
552 Out << "\n/* External Global Variable Declarations */\n";
553 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
554 if (I->hasExternalLinkage()) {
556 printType(I->getType()->getElementType(), getValueName(I));
562 // Function declarations
564 Out << "\n/* Function Declarations */\n";
566 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
567 printFunctionSignature(I, true);
572 // Print Malloc prototype if needed
574 Out << "\n/* Malloc to make sun happy */\n";
575 Out << "extern void * malloc(size_t);\n\n";
578 // Output the global variable declerations
580 Out << "\n\n/* Global Variable Declerations */\n";
581 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
582 if (!I->isExternal()) {
584 printType(I->getType()->getElementType(), getValueName(I));
591 // Output the global variable definitions and contents...
593 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
594 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
595 if (!I->isExternal()) {
596 if (I->hasInternalLinkage())
598 printType(I->getType()->getElementType(), getValueName(I));
601 writeOperand(I->getInitializer());
606 // Output all of the functions...
608 Out << "\n\n/* Function Bodies */\n";
609 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
615 /// printSymbolTable - Run through symbol table looking for type names. If a
616 /// type name is found, emit it's declaration...
618 void CWriter::printSymbolTable(const SymbolTable &ST) {
619 // If there are no type names, exit early.
620 if (ST.find(Type::TypeTy) == ST.end())
623 // We are only interested in the type plane of the symbol table...
624 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
625 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
627 // Print out forward declarations for structure types before anything else!
628 Out << "/* Structure forward decls */\n";
629 for (; I != End; ++I)
630 if (const Type *STy = dyn_cast<StructType>(I->second)) {
631 string Name = "struct l_" + makeNameProper(I->first);
632 Out << Name << ";\n";
633 TypeNames.insert(std::make_pair(STy, Name));
638 // Now we can print out typedefs...
639 Out << "/* Typedefs */\n";
640 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
641 const Type *Ty = cast<Type>(I->second);
642 string Name = "l_" + makeNameProper(I->first);
650 // Keep track of which structures have been printed so far...
651 std::set<const StructType *> StructPrinted;
653 // Loop over all structures then push them into the stack so they are
654 // printed in the correct order.
656 Out << "/* Structure contents */\n";
657 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
658 if (const StructType *STy = dyn_cast<StructType>(I->second))
659 printContainedStructs(STy, StructPrinted);
662 // Push the struct onto the stack and recursively push all structs
663 // this one depends on.
664 void CWriter::printContainedStructs(const Type *Ty,
665 std::set<const StructType*> &StructPrinted){
666 if (const StructType *STy = dyn_cast<StructType>(Ty)){
667 //Check to see if we have already printed this struct
668 if (StructPrinted.count(STy) == 0) {
669 // Print all contained types first...
670 for (StructType::ElementTypes::const_iterator
671 I = STy->getElementTypes().begin(),
672 E = STy->getElementTypes().end(); I != E; ++I) {
673 const Type *Ty1 = I->get();
674 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
675 printContainedStructs(Ty1, StructPrinted);
678 //Print structure type out..
679 StructPrinted.insert(STy);
680 string Name = TypeNames[STy];
681 printType(STy, Name, true);
685 // If it is an array, check contained types and continue
686 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
687 const Type *Ty1 = ATy->getElementType();
688 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
689 printContainedStructs(Ty1, StructPrinted);
694 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
695 // If the program provides it's own malloc prototype we don't need
696 // to include the general one.
697 if (getValueName(F) == "malloc")
699 if (F->hasInternalLinkage()) Out << "static ";
701 // Loop over the arguments, printing them...
702 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
704 // Print out the return type and name...
705 printType(F->getReturnType());
706 Out << getValueName(F) << "(";
708 if (!F->isExternal()) {
711 if (F->abegin()->hasName() || !Prototype)
712 ArgName = getValueName(F->abegin());
714 printType(F->afront().getType(), ArgName);
716 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
719 if (I->hasName() || !Prototype)
720 ArgName = getValueName(I);
723 printType(I->getType(), ArgName);
727 // Loop over the arguments, printing them...
728 for (FunctionType::ParamTypes::const_iterator I =
729 FT->getParamTypes().begin(),
730 E = FT->getParamTypes().end(); I != E; ++I) {
731 if (I != FT->getParamTypes().begin()) Out << ", ";
736 // Finish printing arguments... if this is a vararg function, print the ...,
737 // unless there are no known types, in which case, we just emit ().
739 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
740 if (FT->getParamTypes().size()) Out << ", ";
741 Out << "..."; // Output varargs portion of signature!
747 void CWriter::printFunction(Function *F) {
748 if (F->isExternal()) return;
750 Table->incorporateFunction(F);
752 printFunctionSignature(F, false);
755 // print local variable information for the function
756 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
757 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
759 printType((*I)->getType(), getValueName(*I));
765 // Scan the function for floating point constants. If any FP constant is used
766 // in the function, we want to redirect it here so that we do not depend on
767 // the precision of the printed form.
769 unsigned FPCounter = 0;
770 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
771 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
772 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
773 double Val = FPC->getValue();
775 FPConstantMap[FPC] = FPCounter; // Number the FP constants
777 if (FPC->getType() == Type::DoubleTy)
778 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
779 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
780 << "; /* " << Val << " */\n";
781 else if (FPC->getType() == Type::FloatTy) {
783 Out << " const ConstantFloatTy FloatConstant" << FPCounter++
784 << " = 0x" << std::hex << *(unsigned*)&fVal << std::dec
785 << "; /* " << Val << " */\n";
787 assert(0 && "Unknown float type!");
792 // print the basic blocks
793 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
794 BasicBlock *Prev = BB->getPrev();
796 // Don't print the label for the basic block if there are no uses, or if the
797 // only terminator use is the precessor basic block's terminator. We have
798 // to scan the use list because PHI nodes use basic blocks too but do not
799 // require a label to be generated.
801 bool NeedsLabel = false;
802 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
804 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
805 if (TI != Prev->getTerminator()) {
810 if (NeedsLabel) Out << getValueName(BB) << ":\n";
812 // Output all of the instructions in the basic block...
813 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
814 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
815 if (II->getType() != Type::VoidTy)
824 // Don't emit prefix or suffix for the terminator...
825 visit(*BB->getTerminator());
829 Table->purgeFunction();
830 FPConstantMap.clear();
833 // Specific Instruction type classes... note that all of the casts are
834 // neccesary because we use the instruction classes as opaque types...
836 void CWriter::visitReturnInst(ReturnInst &I) {
837 // Don't output a void return if this is the last basic block in the function
838 if (I.getNumOperands() == 0 &&
839 &*--I.getParent()->getParent()->end() == I.getParent() &&
840 !I.getParent()->size() == 1) {
845 if (I.getNumOperands()) {
847 writeOperand(I.getOperand(0));
852 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
853 // If PHI nodes need copies, we need the copy code...
854 if (isa<PHINode>(To->front()) ||
855 From->getNext() != To) // Not directly successor, need goto
858 // Otherwise we don't need the code.
862 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
864 for (BasicBlock::iterator I = Succ->begin();
865 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
866 // now we have to do the printing
867 Out << string(Indent, ' ');
869 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
870 Out << "; /* for PHI node */\n";
873 if (CurBB->getNext() != Succ) {
874 Out << string(Indent, ' ') << " goto ";
880 // Brach instruction printing - Avoid printing out a brach to a basic block that
881 // immediately succeeds the current one.
883 void CWriter::visitBranchInst(BranchInst &I) {
884 if (I.isConditional()) {
885 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
887 writeOperand(I.getCondition());
890 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
892 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
893 Out << " } else {\n";
894 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
897 // First goto not neccesary, assume second one is...
899 writeOperand(I.getCondition());
902 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
907 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
913 void CWriter::visitBinaryOperator(Instruction &I) {
914 // binary instructions, shift instructions, setCond instructions.
915 if (isa<PointerType>(I.getType())) {
917 printType(I.getType());
921 if (isa<PointerType>(I.getType())) Out << "(long long)";
922 writeOperand(I.getOperand(0));
924 switch (I.getOpcode()) {
925 case Instruction::Add: Out << " + "; break;
926 case Instruction::Sub: Out << " - "; break;
927 case Instruction::Mul: Out << "*"; break;
928 case Instruction::Div: Out << "/"; break;
929 case Instruction::Rem: Out << "%"; break;
930 case Instruction::And: Out << " & "; break;
931 case Instruction::Or: Out << " | "; break;
932 case Instruction::Xor: Out << " ^ "; break;
933 case Instruction::SetEQ: Out << " == "; break;
934 case Instruction::SetNE: Out << " != "; break;
935 case Instruction::SetLE: Out << " <= "; break;
936 case Instruction::SetGE: Out << " >= "; break;
937 case Instruction::SetLT: Out << " < "; break;
938 case Instruction::SetGT: Out << " > "; break;
939 case Instruction::Shl : Out << " << "; break;
940 case Instruction::Shr : Out << " >> "; break;
941 default: std::cerr << "Invalid operator type!" << I; abort();
944 if (isa<PointerType>(I.getType())) Out << "(long long)";
945 writeOperand(I.getOperand(1));
948 void CWriter::visitCastInst(CastInst &I) {
950 printType(I.getType(), string(""),/*ignoreName*/false, /*namedContext*/false);
952 writeOperand(I.getOperand(0));
955 void CWriter::visitCallInst(CallInst &I) {
956 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
957 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
958 const Type *RetTy = FTy->getReturnType();
960 writeOperand(I.getOperand(0));
963 if (I.getNumOperands() > 1) {
964 writeOperand(I.getOperand(1));
966 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
968 writeOperand(I.getOperand(op));
974 void CWriter::visitMallocInst(MallocInst &I) {
976 printType(I.getType());
977 Out << ")malloc(sizeof(";
978 printType(I.getType()->getElementType());
981 if (I.isArrayAllocation()) {
983 writeOperand(I.getOperand(0));
988 void CWriter::visitAllocaInst(AllocaInst &I) {
990 printType(I.getType());
991 Out << ") alloca(sizeof(";
992 printType(I.getType()->getElementType());
994 if (I.isArrayAllocation()) {
996 writeOperand(I.getOperand(0));
1001 void CWriter::visitFreeInst(FreeInst &I) {
1003 writeOperand(I.getOperand(0));
1007 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1008 User::op_iterator E) {
1009 bool HasImplicitAddress = false;
1010 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1011 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1012 HasImplicitAddress = true;
1013 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1014 HasImplicitAddress = true;
1015 Ptr = CPR->getValue(); // Get to the global...
1019 if (!HasImplicitAddress)
1020 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1022 writeOperandInternal(Ptr);
1026 const Constant *CI = dyn_cast<Constant>(I->get());
1027 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1030 writeOperandInternal(Ptr);
1032 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1034 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1037 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1038 "Can only have implicit address with direct accessing");
1040 if (HasImplicitAddress) {
1042 } else if (CI && CI->isNullValue() && I+1 != E) {
1043 // Print out the -> operator if possible...
1044 if ((*(I+1))->getType() == Type::UByteTy) {
1045 Out << (HasImplicitAddress ? "." : "->");
1046 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1052 if ((*I)->getType() == Type::LongTy) {
1057 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1061 void CWriter::visitLoadInst(LoadInst &I) {
1063 writeOperand(I.getOperand(0));
1066 void CWriter::visitStoreInst(StoreInst &I) {
1068 writeOperand(I.getPointerOperand());
1070 writeOperand(I.getOperand(0));
1073 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1075 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1078 //===----------------------------------------------------------------------===//
1079 // External Interface declaration
1080 //===----------------------------------------------------------------------===//
1082 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }