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/iMemory.h"
12 #include "llvm/iTerminators.h"
13 #include "llvm/iPHINode.h"
14 #include "llvm/iOther.h"
15 #include "llvm/iOperators.h"
16 #include "llvm/Pass.h"
17 #include "llvm/SymbolTable.h"
18 #include "llvm/SlotCalculator.h"
19 #include "llvm/Analysis/FindUsedTypes.h"
20 #include "llvm/Analysis/ConstantsScanner.h"
21 #include "llvm/Support/InstVisitor.h"
22 #include "llvm/Support/InstIterator.h"
23 #include "Support/StringExtras.h"
24 #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;
39 map<const ConstantFP *, unsigned> FPConstantMap;
41 CWriter(ostream &o) : Out(o) {}
43 void getAnalysisUsage(AnalysisUsage &AU) const {
45 AU.addRequired<FindUsedTypes>();
48 virtual bool run(Module &M) {
50 Table = new SlotCalculator(&M, false);
53 // Ensure that all structure types have names...
54 bool Changed = nameAllUsedStructureTypes(M);
62 MangledGlobals.clear();
66 ostream &printType(const Type *Ty, const string &VariableName = "",
67 bool IgnoreName = false, bool namedContext = true);
69 void writeOperand(Value *Operand);
70 void writeOperandInternal(Value *Operand);
72 string getValueName(const Value *V);
75 bool nameAllUsedStructureTypes(Module &M);
76 void printModule(Module *M);
77 void printSymbolTable(const SymbolTable &ST);
78 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
79 void printGlobal(const GlobalVariable *GV);
80 void printFunctionSignature(const Function *F, bool Prototype);
82 void printFunction(Function *);
84 void printConstant(Constant *CPV);
85 void printConstantArray(ConstantArray *CPA);
87 // isInlinableInst - Attempt to inline instructions into their uses to build
88 // trees as much as possible. To do this, we have to consistently decide
89 // what is acceptable to inline, so that variable declarations don't get
90 // printed and an extra copy of the expr is not emitted.
92 static bool isInlinableInst(const Instruction &I) {
93 // Must be an expression, must be used exactly once. If it is dead, we
94 // emit it inline where it would go.
95 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
96 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I))
99 // Only inline instruction it it's use is in the same BB as the inst.
100 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
103 // Instruction visitation functions
104 friend class InstVisitor<CWriter>;
106 void visitReturnInst(ReturnInst &I);
107 void visitBranchInst(BranchInst &I);
109 void visitPHINode(PHINode &I) {}
110 void visitBinaryOperator(Instruction &I);
112 void visitCastInst (CastInst &I);
113 void visitCallInst (CallInst &I);
114 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
116 void visitMallocInst(MallocInst &I);
117 void visitAllocaInst(AllocaInst &I);
118 void visitFreeInst (FreeInst &I);
119 void visitLoadInst (LoadInst &I);
120 void visitStoreInst (StoreInst &I);
121 void visitGetElementPtrInst(GetElementPtrInst &I);
123 void visitInstruction(Instruction &I) {
124 std::cerr << "C Writer does not know about " << I;
128 void outputLValue(Instruction *I) {
129 Out << " " << getValueName(I) << " = ";
131 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
133 void printIndexingExpression(Value *Ptr, User::op_iterator I,
134 User::op_iterator E);
138 // We dont want identifier names with ., space, - in them.
139 // So we replace them with _
140 static string makeNameProper(string x) {
142 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
144 case '.': tmp += "d_"; break;
145 case ' ': tmp += "s_"; break;
146 case '-': tmp += "D_"; break;
153 string CWriter::getValueName(const Value *V) {
154 if (V->hasName()) { // Print out the label if it exists...
155 if (isa<GlobalValue>(V) && // Do not mangle globals...
156 cast<GlobalValue>(V)->hasExternalLinkage() && // Unless it's internal or
157 !MangledGlobals.count(V)) // Unless the name would collide if we don't
158 return makeNameProper(V->getName());
160 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
161 makeNameProper(V->getName());
164 int Slot = Table->getValSlot(V);
165 assert(Slot >= 0 && "Invalid value!");
166 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
169 // A pointer type should not use parens around *'s alone, e.g., (**)
170 inline bool ptrTypeNameNeedsParens(const string &NameSoFar) {
171 return (NameSoFar.find_last_not_of('*') != std::string::npos);
174 // Pass the Type* and the variable name and this prints out the variable
177 ostream &CWriter::printType(const Type *Ty, const string &NameSoFar,
178 bool IgnoreName, bool namedContext) {
179 if (Ty->isPrimitiveType())
180 switch (Ty->getPrimitiveID()) {
181 case Type::VoidTyID: return Out << "void " << NameSoFar;
182 case Type::BoolTyID: return Out << "bool " << NameSoFar;
183 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
184 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
185 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
186 case Type::ShortTyID: return Out << "short " << NameSoFar;
187 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
188 case Type::IntTyID: return Out << "int " << NameSoFar;
189 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
190 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
191 case Type::FloatTyID: return Out << "float " << NameSoFar;
192 case Type::DoubleTyID: return Out << "double " << NameSoFar;
194 std::cerr << "Unknown primitive type: " << Ty << "\n";
198 // Check to see if the type is named.
199 if (!IgnoreName || isa<OpaqueType>(Ty)) {
200 map<const Type *, string>::iterator I = TypeNames.find(Ty);
201 if (I != TypeNames.end()) {
202 return Out << I->second << " " << NameSoFar;
206 switch (Ty->getPrimitiveID()) {
207 case Type::FunctionTyID: {
208 const FunctionType *MTy = cast<FunctionType>(Ty);
209 printType(MTy->getReturnType(), "");
210 Out << " " << NameSoFar << " (";
212 for (FunctionType::ParamTypes::const_iterator
213 I = MTy->getParamTypes().begin(),
214 E = MTy->getParamTypes().end(); I != E; ++I) {
215 if (I != MTy->getParamTypes().begin())
219 if (MTy->isVarArg()) {
220 if (!MTy->getParamTypes().empty())
226 case Type::StructTyID: {
227 const StructType *STy = cast<StructType>(Ty);
228 Out << NameSoFar + " {\n";
230 for (StructType::ElementTypes::const_iterator
231 I = STy->getElementTypes().begin(),
232 E = STy->getElementTypes().end(); I != E; ++I) {
234 printType(*I, "field" + utostr(Idx++));
240 case Type::PointerTyID: {
241 const PointerType *PTy = cast<PointerType>(Ty);
242 std::string ptrName = "*" + NameSoFar;
244 // Do not need parens around "* NameSoFar" if NameSoFar consists only
245 // of zero or more '*' chars *and* this is not an unnamed pointer type
246 // such as the result type in a cast statement. Otherwise, enclose in ( ).
247 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
248 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
249 ptrName = "(" + ptrName + ")"; //
251 return printType(PTy->getElementType(), ptrName);
254 case Type::ArrayTyID: {
255 const ArrayType *ATy = cast<ArrayType>(Ty);
256 unsigned NumElements = ATy->getNumElements();
257 return printType(ATy->getElementType(),
258 NameSoFar + "[" + utostr(NumElements) + "]");
261 case Type::OpaqueTyID: {
262 static int Count = 0;
263 string TyName = "struct opaque_" + itostr(Count++);
264 assert(TypeNames.find(Ty) == TypeNames.end());
265 TypeNames[Ty] = TyName;
266 return Out << TyName << " " << NameSoFar;
269 assert(0 && "Unhandled case in getTypeProps!");
276 void CWriter::printConstantArray(ConstantArray *CPA) {
278 // As a special case, print the array as a string if it is an array of
279 // ubytes or an array of sbytes with positive values.
281 const Type *ETy = CPA->getType()->getElementType();
282 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
284 // Make sure the last character is a null char, as automatically added by C
285 if (CPA->getNumOperands() == 0 ||
286 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
291 // Do not include the last character, which we know is null
292 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
293 unsigned char C = (ETy == Type::SByteTy) ?
294 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
295 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
304 case '\n': Out << "\\n"; break;
305 case '\t': Out << "\\t"; break;
306 case '\r': Out << "\\r"; break;
307 case '\v': Out << "\\v"; break;
308 case '\a': Out << "\\a"; break;
309 case '\"': Out << "\\\""; break;
310 case '\'': Out << "\\\'"; break;
313 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
314 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
322 if (CPA->getNumOperands()) {
324 printConstant(cast<Constant>(CPA->getOperand(0)));
325 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
327 printConstant(cast<Constant>(CPA->getOperand(i)));
335 // printConstant - The LLVM Constant to C Constant converter.
336 void CWriter::printConstant(Constant *CPV) {
337 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
338 switch (CE->getOpcode()) {
339 case Instruction::Cast:
341 printType(CPV->getType());
343 printConstant(cast<Constant>(CPV->getOperand(0)));
347 case Instruction::GetElementPtr:
349 printIndexingExpression(CPV->getOperand(0),
350 CPV->op_begin()+1, CPV->op_end());
353 case Instruction::Add:
355 printConstant(cast<Constant>(CPV->getOperand(0)));
357 printConstant(cast<Constant>(CPV->getOperand(1)));
360 case Instruction::Sub:
362 printConstant(cast<Constant>(CPV->getOperand(0)));
364 printConstant(cast<Constant>(CPV->getOperand(1)));
369 std::cerr << "CWriter Error: Unhandled constant expression: "
375 switch (CPV->getType()->getPrimitiveID()) {
377 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
378 case Type::SByteTyID:
379 case Type::ShortTyID:
381 Out << cast<ConstantSInt>(CPV)->getValue(); break;
383 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
385 case Type::UByteTyID:
386 case Type::UShortTyID:
387 Out << cast<ConstantUInt>(CPV)->getValue(); break;
389 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
390 case Type::ULongTyID:
391 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
393 case Type::FloatTyID:
394 case Type::DoubleTyID: {
395 ConstantFP *FPC = cast<ConstantFP>(CPV);
396 map<const ConstantFP *, unsigned>::iterator I = FPConstantMap.find(FPC);
397 if (I != FPConstantMap.end()) {
398 // Because of FP precision problems we must load from a stack allocated
399 // value that holds the value in hex.
400 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
401 << "*)&FloatConstant" << I->second << ")";
403 Out << FPC->getValue();
408 case Type::ArrayTyID:
409 printConstantArray(cast<ConstantArray>(CPV));
412 case Type::StructTyID: {
414 if (CPV->getNumOperands()) {
416 printConstant(cast<Constant>(CPV->getOperand(0)));
417 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
419 printConstant(cast<Constant>(CPV->getOperand(i)));
426 case Type::PointerTyID:
427 if (isa<ConstantPointerNull>(CPV)) {
429 printType(CPV->getType(), "");
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"
539 << "\n\n/* Global Declarations */\n";
541 // First output all the declarations for the program, because C requires
542 // Functions & globals to be declared before they are used.
545 // Loop over the symbol table, emitting all named constants...
546 if (M->hasSymbolTable())
547 printSymbolTable(*M->getSymbolTable());
549 // Global variable declarations...
551 Out << "\n/* External Global Variable Declarations */\n";
552 // Needed for malloc to work on sun.
553 Out << "extern void * malloc(size_t);\n";
554 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
555 if (I->hasExternalLinkage()) {
557 printType(I->getType()->getElementType(), getValueName(I));
563 // Function declarations
565 Out << "\n/* Function Declarations */\n";
566 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
567 printFunctionSignature(I, true);
572 // Output the global variable definitions and contents...
574 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
575 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
576 if (I->hasInternalLinkage())
578 printType(I->getType()->getElementType(), getValueName(I));
580 if (I->hasInitializer()) {
582 writeOperand(I->getInitializer());
588 // Output all of the functions...
590 Out << "\n\n/* Function Bodies */\n";
591 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
597 /// printSymbolTable - Run through symbol table looking for type names. If a
598 /// type name is found, emit it's declaration...
600 void CWriter::printSymbolTable(const SymbolTable &ST) {
601 // If there are no type names, exit early.
602 if (ST.find(Type::TypeTy) == ST.end())
605 // We are only interested in the type plane of the symbol table...
606 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
607 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
609 // Print out forward declarations for structure types before anything else!
610 Out << "/* Structure forward decls */\n";
611 for (; I != End; ++I)
612 if (const Type *STy = dyn_cast<StructType>(I->second)) {
613 string Name = "struct l_" + makeNameProper(I->first);
614 Out << Name << ";\n";
615 TypeNames.insert(std::make_pair(STy, Name));
620 // Now we can print out typedefs...
621 Out << "/* Typedefs */\n";
622 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
623 const Type *Ty = cast<Type>(I->second);
624 string Name = "l_" + makeNameProper(I->first);
632 // Keep track of which structures have been printed so far...
633 std::set<const StructType *> StructPrinted;
635 // Loop over all structures then push them into the stack so they are
636 // printed in the correct order.
638 Out << "/* Structure contents */\n";
639 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
640 if (const StructType *STy = dyn_cast<StructType>(I->second))
641 printContainedStructs(STy, StructPrinted);
644 // Push the struct onto the stack and recursively push all structs
645 // this one depends on.
646 void CWriter::printContainedStructs(const Type *Ty,
647 std::set<const StructType*> &StructPrinted){
648 if (const StructType *STy = dyn_cast<StructType>(Ty)){
649 //Check to see if we have already printed this struct
650 if (StructPrinted.count(STy) == 0) {
651 // Print all contained types first...
652 for (StructType::ElementTypes::const_iterator
653 I = STy->getElementTypes().begin(),
654 E = STy->getElementTypes().end(); I != E; ++I) {
655 const Type *Ty1 = I->get();
656 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
657 printContainedStructs(Ty1, StructPrinted);
660 //Print structure type out..
661 StructPrinted.insert(STy);
662 string Name = TypeNames[STy];
663 printType(STy, Name, true);
667 // If it is an array, check contained types and continue
668 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
669 const Type *Ty1 = ATy->getElementType();
670 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
671 printContainedStructs(Ty1, StructPrinted);
676 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
677 if (F->hasInternalLinkage()) Out << "static ";
679 // Loop over the arguments, printing them...
680 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
682 // Print out the return type and name...
683 printType(F->getReturnType());
684 Out << getValueName(F) << "(";
686 if (!F->isExternal()) {
689 if (F->abegin()->hasName() || !Prototype)
690 ArgName = getValueName(F->abegin());
692 printType(F->afront().getType(), ArgName);
694 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
697 if (I->hasName() || !Prototype)
698 ArgName = getValueName(I);
701 printType(I->getType(), ArgName);
705 // Loop over the arguments, printing them...
706 for (FunctionType::ParamTypes::const_iterator I =
707 FT->getParamTypes().begin(),
708 E = FT->getParamTypes().end(); I != E; ++I) {
709 if (I != FT->getParamTypes().begin()) Out << ", ";
714 // Finish printing arguments... if this is a vararg function, print the ...,
715 // unless there are no known types, in which case, we just emit ().
717 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
718 if (FT->getParamTypes().size()) Out << ", ";
719 Out << "..."; // Output varargs portion of signature!
725 void CWriter::printFunction(Function *F) {
726 if (F->isExternal()) return;
728 Table->incorporateFunction(F);
730 printFunctionSignature(F, false);
733 // print local variable information for the function
734 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
735 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
737 printType((*I)->getType(), getValueName(*I));
743 // Scan the function for floating point constants. If any FP constant is used
744 // in the function, we want to redirect it here so that we do not depend on
745 // the precision of the printed form.
747 unsigned FPCounter = 0;
748 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
749 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
750 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
751 double Val = FPC->getValue();
753 FPConstantMap[FPC] = FPCounter; // Number the FP constants
754 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
755 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
756 << "; /* " << Val << " */\n";
761 // print the basic blocks
762 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
763 BasicBlock *Prev = BB->getPrev();
765 // Don't print the label for the basic block if there are no uses, or if the
766 // only terminator use is the precessor basic block's terminator. We have
767 // to scan the use list because PHI nodes use basic blocks too but do not
768 // require a label to be generated.
770 bool NeedsLabel = false;
771 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
773 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
774 if (TI != Prev->getTerminator()) {
779 if (NeedsLabel) Out << getValueName(BB) << ":\n";
781 // Output all of the instructions in the basic block...
782 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
783 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
784 if (II->getType() != Type::VoidTy)
793 // Don't emit prefix or suffix for the terminator...
794 visit(*BB->getTerminator());
798 Table->purgeFunction();
799 FPConstantMap.clear();
802 // Specific Instruction type classes... note that all of the casts are
803 // neccesary because we use the instruction classes as opaque types...
805 void CWriter::visitReturnInst(ReturnInst &I) {
806 // Don't output a void return if this is the last basic block in the function
807 if (I.getNumOperands() == 0 &&
808 &*--I.getParent()->getParent()->end() == I.getParent() &&
809 !I.getParent()->size() == 1) {
814 if (I.getNumOperands()) {
816 writeOperand(I.getOperand(0));
821 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
822 // If PHI nodes need copies, we need the copy code...
823 if (isa<PHINode>(To->front()) ||
824 From->getNext() != To) // Not directly successor, need goto
827 // Otherwise we don't need the code.
831 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
833 for (BasicBlock::iterator I = Succ->begin();
834 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
835 // now we have to do the printing
836 Out << string(Indent, ' ');
838 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
839 Out << "; /* for PHI node */\n";
842 if (CurBB->getNext() != Succ) {
843 Out << string(Indent, ' ') << " goto ";
849 // Brach instruction printing - Avoid printing out a brach to a basic block that
850 // immediately succeeds the current one.
852 void CWriter::visitBranchInst(BranchInst &I) {
853 if (I.isConditional()) {
854 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
856 writeOperand(I.getCondition());
859 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
861 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
862 Out << " } else {\n";
863 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
866 // First goto not neccesary, assume second one is...
868 writeOperand(I.getCondition());
871 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
876 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
882 void CWriter::visitBinaryOperator(Instruction &I) {
883 // binary instructions, shift instructions, setCond instructions.
884 if (isa<PointerType>(I.getType())) {
886 printType(I.getType());
890 if (isa<PointerType>(I.getType())) Out << "(long long)";
891 writeOperand(I.getOperand(0));
893 switch (I.getOpcode()) {
894 case Instruction::Add: Out << " + "; break;
895 case Instruction::Sub: Out << " - "; break;
896 case Instruction::Mul: Out << "*"; break;
897 case Instruction::Div: Out << "/"; break;
898 case Instruction::Rem: Out << "%"; break;
899 case Instruction::And: Out << " & "; break;
900 case Instruction::Or: Out << " | "; break;
901 case Instruction::Xor: Out << " ^ "; break;
902 case Instruction::SetEQ: Out << " == "; break;
903 case Instruction::SetNE: Out << " != "; break;
904 case Instruction::SetLE: Out << " <= "; break;
905 case Instruction::SetGE: Out << " >= "; break;
906 case Instruction::SetLT: Out << " < "; break;
907 case Instruction::SetGT: Out << " > "; break;
908 case Instruction::Shl : Out << " << "; break;
909 case Instruction::Shr : Out << " >> "; break;
910 default: std::cerr << "Invalid operator type!" << I; abort();
913 if (isa<PointerType>(I.getType())) Out << "(long long)";
914 writeOperand(I.getOperand(1));
917 void CWriter::visitCastInst(CastInst &I) {
919 printType(I.getType(), string(""),/*ignoreName*/false, /*namedContext*/false);
921 writeOperand(I.getOperand(0));
924 void CWriter::visitCallInst(CallInst &I) {
925 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
926 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
927 const Type *RetTy = FTy->getReturnType();
929 writeOperand(I.getOperand(0));
932 if (I.getNumOperands() > 1) {
933 writeOperand(I.getOperand(1));
935 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
937 writeOperand(I.getOperand(op));
943 void CWriter::visitMallocInst(MallocInst &I) {
945 printType(I.getType());
946 Out << ")malloc(sizeof(";
947 printType(I.getType()->getElementType());
950 if (I.isArrayAllocation()) {
952 writeOperand(I.getOperand(0));
957 void CWriter::visitAllocaInst(AllocaInst &I) {
959 printType(I.getType());
960 Out << ") alloca(sizeof(";
961 printType(I.getType()->getElementType());
963 if (I.isArrayAllocation()) {
965 writeOperand(I.getOperand(0));
970 void CWriter::visitFreeInst(FreeInst &I) {
972 writeOperand(I.getOperand(0));
976 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
977 User::op_iterator E) {
978 bool HasImplicitAddress = false;
979 // If accessing a global value with no indexing, avoid *(&GV) syndrome
980 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
981 HasImplicitAddress = true;
982 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
983 HasImplicitAddress = true;
984 Ptr = CPR->getValue(); // Get to the global...
988 if (!HasImplicitAddress)
989 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
991 writeOperandInternal(Ptr);
995 const Constant *CI = dyn_cast<Constant>(I->get());
996 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
999 writeOperandInternal(Ptr);
1001 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1003 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1006 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1007 "Can only have implicit address with direct accessing");
1009 if (HasImplicitAddress) {
1011 } else if (CI && CI->isNullValue() && I+1 != E) {
1012 // Print out the -> operator if possible...
1013 if ((*(I+1))->getType() == Type::UByteTy) {
1014 Out << (HasImplicitAddress ? "." : "->");
1015 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1021 if ((*I)->getType() == Type::LongTy) {
1026 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1030 void CWriter::visitLoadInst(LoadInst &I) {
1032 writeOperand(I.getOperand(0));
1035 void CWriter::visitStoreInst(StoreInst &I) {
1037 writeOperand(I.getPointerOperand());
1039 writeOperand(I.getOperand(0));
1042 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1044 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1047 //===----------------------------------------------------------------------===//
1048 // External Interface declaration
1049 //===----------------------------------------------------------------------===//
1051 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }