1 //===-- Writer.cpp - Library for writing C files --------------------------===//
3 // This library implements the functionality defined in llvm/Assembly/CWriter.h
6 // TODO : Recursive types.
8 //===-----------------------------------------------------------------------==//
10 #include "llvm/Assembly/CWriter.h"
11 #include "CLocalVars.h"
12 #include "llvm/SlotCalculator.h"
13 #include "llvm/Constants.h"
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/Module.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/Function.h"
18 #include "llvm/Argument.h"
19 #include "llvm/BasicBlock.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/iTerminators.h"
22 #include "llvm/iPHINode.h"
23 #include "llvm/iOther.h"
24 #include "llvm/iOperators.h"
25 #include "llvm/SymbolTable.h"
26 #include "llvm/Support/InstVisitor.h"
27 #include "Support/StringExtras.h"
28 #include "Support/STLExtras.h"
37 //===-----------------------------------------------------------------------==//
39 // Implementation of the CLocalVars methods
41 // Appends a variable to the LocalVars map if it does not already exist
42 // Also check that the type exists on the map.
43 void CLocalVars::addLocalVar(const Type *t, const string & var) {
44 if (!LocalVars.count(t) ||
45 find(LocalVars[t].begin(), LocalVars[t].end(), var)
46 == LocalVars[t].end()) {
47 LocalVars[t].push_back(var);
51 static string calcTypeNameVar(const Type *Ty,
52 map<const Type *, string> &TypeNames,
53 string VariableName, string NameSoFar);
55 static std::string getConstStrValue(const Constant* CPV);
58 // We dont want identifier names with ., space, - in them.
59 // So we replace them with _
60 static string makeNameProper(string x) {
62 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++) {
75 static std::string getConstArrayStrValue(const Constant* CPV) {
78 // As a special case, print the array as a string if it is an array of
79 // ubytes or an array of sbytes with positive values.
81 const Type *ETy = cast<ArrayType>(CPV->getType())->getElementType();
82 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
84 if (ETy == Type::SByteTy) {
85 for (unsigned i = 0; i < CPV->getNumOperands(); ++i)
86 if (ETy == Type::SByteTy &&
87 cast<ConstantSInt>(CPV->getOperand(i))->getValue() < 0) {
93 // Make sure the last character is a null char, as automatically added by C
94 if (CPV->getNumOperands() == 0 ||
95 !cast<Constant>(*(CPV->op_end()-1))->isNullValue())
101 // Do not include the last character, which we know is null
102 for (unsigned i = 0, e = CPV->getNumOperands()-1; i != e; ++i) {
103 unsigned char C = (ETy == Type::SByteTy) ?
104 (unsigned char)cast<ConstantSInt>(CPV->getOperand(i))->getValue() :
105 (unsigned char)cast<ConstantUInt>(CPV->getOperand(i))->getValue();
111 case '\n': Result += "\\n"; break;
112 case '\t': Result += "\\t"; break;
113 case '\r': Result += "\\r"; break;
114 case '\v': Result += "\\v"; break;
115 case '\a': Result += "\\a"; break;
118 Result += ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
119 Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
128 if (CPV->getNumOperands()) {
129 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
130 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
131 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
139 static std::string getConstStructStrValue(const Constant* CPV) {
140 std::string Result = "{";
141 if (CPV->getNumOperands()) {
142 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
143 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
144 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
147 return Result + " }";
150 // our own getStrValue function for constant initializers
151 static std::string getConstStrValue(const Constant* CPV) {
152 // Does not handle null pointers, that needs to be checked explicitly
154 if (CPV == ConstantBool::False)
156 else if (CPV == ConstantBool::True)
159 else if (isa<ConstantArray>(CPV)) {
160 tempstr = getConstArrayStrValue(CPV);
162 else if (isa<ConstantStruct>(CPV)) {
163 tempstr = getConstStructStrValue(CPV);
165 else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(CPV)) {
166 tempstr = utostr(CUI->getValue());
168 else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CPV)) {
169 tempstr = itostr(CSI->getValue());
171 else if (ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
172 tempstr = ftostr(CFP->getValue());
175 if (CPV->getType() == Type::ULongTy)
177 else if (CPV->getType() == Type::LongTy)
179 else if (CPV->getType() == Type::UIntTy ||
180 CPV->getType() == Type::UShortTy)
188 // Essentially pass the Type* variable, an empty typestack and this prints
190 static string calcTypeName(const Type *Ty, map<const Type *, string> &TypeNames,
191 string &FunctionInfo) {
193 // Takin' care of the fact that boolean would be int in C
194 // and that ushort would be unsigned short etc.
197 if (Ty->isPrimitiveType())
198 switch (Ty->getPrimitiveID()) {
199 case Type::VoidTyID: return "void";
200 case Type::BoolTyID: return "bool";
201 case Type::UByteTyID: return "unsigned char";
202 case Type::SByteTyID: return "signed char";
203 case Type::UShortTyID: return "unsigned short";
204 case Type::ShortTyID: return "short";
205 case Type::UIntTyID: return "unsigned";
206 case Type::IntTyID: return "int";
207 case Type::ULongTyID: return "unsigned long long";
208 case Type::LongTyID: return "signed long long";
209 case Type::FloatTyID: return "float";
210 case Type::DoubleTyID: return "double";
211 default : assert(0 && "Unknown primitive type!");
214 // Check to see if the type is named.
215 map<const Type *, string>::iterator I = TypeNames.find(Ty);
216 if (I != TypeNames.end())
221 switch (Ty->getPrimitiveID()) {
222 case Type::FunctionTyID: {
223 const FunctionType *MTy = cast<const FunctionType>(Ty);
224 Result = calcTypeName(MTy->getReturnType(), TypeNames, MInfo);
226 Result += ") " + MInfo;
228 FunctionInfo += " (";
229 for (FunctionType::ParamTypes::const_iterator
230 I = MTy->getParamTypes().begin(),
231 E = MTy->getParamTypes().end(); I != E; ++I) {
232 if (I != MTy->getParamTypes().begin())
233 FunctionInfo += ", ";
235 FunctionInfo += calcTypeName(*I, TypeNames, MInfo);
237 Result += ") " + MInfo;
239 if (MTy->isVarArg()) {
240 if (!MTy->getParamTypes().empty())
241 FunctionInfo += ", ";
242 FunctionInfo += "...";
247 case Type::StructTyID: {
249 const StructType *STy = cast<const StructType>(Ty);
250 Result = " struct {\n ";
252 for (StructType::ElementTypes::const_iterator
253 I = STy->getElementTypes().begin(),
254 E = STy->getElementTypes().end(); I != E; ++I) {
255 Result += calcTypeNameVar(*I, TypeNames,
256 "field" + itostr(indx++), tempstr);
262 case Type::PointerTyID:
263 Result = calcTypeName(cast<const PointerType>(Ty)->getElementType(),
267 case Type::ArrayTyID: {
268 const ArrayType *ATy = cast<const ArrayType>(Ty);
269 int NumElements = ATy->getNumElements();
270 Result = calcTypeName(ATy->getElementType(), TypeNames, MInfo);
275 assert(0 && "Unhandled case in getTypeProps!");
283 // Pass the Type* variable and and the variable name and this prints out the
284 // variable declaration.
285 // This is different from calcTypeName because if you need to declare an array
286 // the size of the array would appear after the variable name itself
287 // For eg. int a[10];
288 static string calcTypeNameVar(const Type *Ty,
289 map<const Type *, string> &TypeNames,
290 string VariableName, string NameSoFar) {
291 if (Ty->isPrimitiveType())
292 switch (Ty->getPrimitiveID()) {
294 return "bool " + NameSoFar + VariableName;
295 case Type::UByteTyID:
296 return "unsigned char " + NameSoFar + VariableName;
297 case Type::SByteTyID:
298 return "signed char " + NameSoFar + VariableName;
299 case Type::UShortTyID:
300 return "unsigned long long " + NameSoFar + VariableName;
301 case Type::ULongTyID:
302 return "unsigned long long " + NameSoFar + VariableName;
304 return "signed long long " + NameSoFar + VariableName;
306 return "unsigned " + NameSoFar + VariableName;
308 return Ty->getDescription() + " " + NameSoFar + VariableName;
311 // Check to see if the type is named.
312 map<const Type *, string>::iterator I = TypeNames.find(Ty);
313 if (I != TypeNames.end())
314 return I->second + " " + NameSoFar + VariableName;
319 switch (Ty->getPrimitiveID()) {
320 case Type::FunctionTyID: {
322 const FunctionType *MTy = cast<const FunctionType>(Ty);
323 Result += calcTypeName(MTy->getReturnType(), TypeNames, MInfo);
325 Result += ") " + MInfo;
326 Result += " " + NameSoFar + VariableName;
328 for (FunctionType::ParamTypes::const_iterator
329 I = MTy->getParamTypes().begin(),
330 E = MTy->getParamTypes().end(); I != E; ++I) {
331 if (I != MTy->getParamTypes().begin())
334 Result += calcTypeName(*I, TypeNames, MInfo);
336 Result += ") " + MInfo;
338 if (MTy->isVarArg()) {
339 if (!MTy->getParamTypes().empty())
346 case Type::StructTyID: {
347 const StructType *STy = cast<const StructType>(Ty);
348 Result = " struct {\n ";
350 for (StructType::ElementTypes::const_iterator
351 I = STy->getElementTypes().begin(),
352 E = STy->getElementTypes().end(); I != E; ++I) {
353 Result += calcTypeNameVar(*I, TypeNames,
354 "field" + itostr(indx++), "");
358 Result += " " + NameSoFar + VariableName;
362 case Type::PointerTyID: {
363 Result = calcTypeNameVar(cast<const PointerType>(Ty)->getElementType(),
365 "(*" + NameSoFar + VariableName + ")");
369 case Type::ArrayTyID: {
370 const ArrayType *ATy = cast<const ArrayType>(Ty);
371 int NumElements = ATy->getNumElements();
372 Result = calcTypeNameVar(ATy->getElementType(), TypeNames,
373 tempstr, NameSoFar + VariableName + "[" +
374 itostr(NumElements) + "]");
378 assert(0 && "Unhandled case in getTypeProps!");
385 // printTypeVarInt - The internal guts of printing out a type that has a
386 // potentially named portion and the variable associated with the type.
387 static ostream &printTypeVarInt(ostream &Out, const Type *Ty,
388 map<const Type *, string> &TypeNames,
389 const string &VariableName) {
390 // Primitive types always print out their description, regardless of whether
391 // they have been named or not.
393 if (Ty->isPrimitiveType())
394 switch (Ty->getPrimitiveID()) {
396 return Out << "bool " << VariableName;
397 case Type::UByteTyID:
398 return Out << "unsigned char " << VariableName;
399 case Type::SByteTyID:
400 return Out << "signed char " << VariableName;
401 case Type::UShortTyID:
402 return Out << "unsigned long long " << VariableName;
403 case Type::ULongTyID:
404 return Out << "unsigned long long " << VariableName;
406 return Out << "signed long long " << VariableName;
408 return Out << "unsigned " << VariableName;
410 return Out << Ty->getDescription() << " " << VariableName;
413 // Check to see if the type is named.
414 map<const Type *, string>::iterator I = TypeNames.find(Ty);
415 if (I != TypeNames.end()) return Out << I->second << " " << VariableName;
417 // Otherwise we have a type that has not been named but is a derived type.
418 // Carefully recurse the type hierarchy to print out any contained symbolic
421 string TypeNameVar, tempstr = "";
422 TypeNameVar = calcTypeNameVar(Ty, TypeNames, VariableName, tempstr);
423 return Out << TypeNameVar;
426 // Internal guts of printing a type name
427 static ostream &printTypeInt(ostream &Out, const Type *Ty,
428 map<const Type *, string> &TypeNames) {
429 // Primitive types always print out their description, regardless of whether
430 // they have been named or not.
432 if (Ty->isPrimitiveType())
433 switch (Ty->getPrimitiveID()) {
435 return Out << "bool";
436 case Type::UByteTyID:
437 return Out << "unsigned char";
438 case Type::SByteTyID:
439 return Out << "signed char";
440 case Type::UShortTyID:
441 return Out << "unsigned short";
442 case Type::ULongTyID:
443 return Out << "unsigned long long";
445 return Out << "signed long long";
447 return Out << "unsigned";
449 return Out << Ty->getDescription();
452 // Check to see if the type is named.
453 map<const Type *, string>::iterator I = TypeNames.find(Ty);
454 if (I != TypeNames.end()) return Out << I->second;
456 // Otherwise we have a type that has not been named but is a derived type.
457 // Carefully recurse the type hierarchy to print out any contained symbolic
461 string TypeName = calcTypeName(Ty, TypeNames, MInfo);
462 // TypeNames.insert(std::make_pair(Ty, TypeName));
463 //Cache type name for later use
465 return Out << TypeName << ")" << MInfo;
467 return Out << TypeName;
472 //Internal CWriter class mimics AssemblyWriter.
475 SlotCalculator &Table;
476 const Module *TheModule;
477 map<const Type *, string> TypeNames;
479 inline CWriter(ostream &o, SlotCalculator &Tab, const Module *M)
480 : Out(o), Table(Tab), TheModule(M) {
483 inline void write(const Module *M) { printModule(M); }
485 ostream& printTypeVar(const Type *Ty, const string &VariableName) {
486 return printTypeVarInt(Out, Ty, TypeNames, VariableName);
491 ostream& printType(const Type *Ty, ostream &Out);
492 void writeOperand(const Value *Operand, ostream &Out,bool PrintName = true);
494 string getValueName(const Value *V);
497 void printModule(const Module *M);
498 void printSymbolTable(const SymbolTable &ST);
499 void printConstant(const Constant *CPV);
500 void printGlobal(const GlobalVariable *GV);
501 void printFunctionSignature(const Function *F);
502 void printFunctionDecl(const Function *F); // Print just the forward decl
503 void printFunctionArgument(const Argument *FA);
505 void printFunction(const Function *);
507 void outputBasicBlock(const BasicBlock *);
509 /* END class CWriter */
512 /* CLASS InstLocalVarsVisitor */
513 class InstLocalVarsVisitor : public InstVisitor<InstLocalVarsVisitor> {
515 void handleTerminator(TerminatorInst *tI, int indx);
519 InstLocalVarsVisitor(CWriter &cw) : CW(cw) {}
521 void visitInstruction(Instruction *I) {
522 if (I->getType() != Type::VoidTy) {
523 string tempostr = CW.getValueName(I);
524 CLV.addLocalVar(I->getType(), tempostr);
528 void visitBranchInst(BranchInst *I) {
529 handleTerminator(I, 0);
530 if (I->isConditional())
531 handleTerminator(I, 1);
536 void InstLocalVarsVisitor::handleTerminator(TerminatorInst *tI,int indx) {
537 BasicBlock *bb = tI->getSuccessor(indx);
539 BasicBlock::const_iterator insIt = bb->begin();
540 while (insIt != bb->end()) {
541 if (const PHINode *pI = dyn_cast<PHINode>(*insIt)) {
543 // Calculate the incoming index for this
544 assert(pI->getBasicBlockIndex(tI->getParent()) != -1);
546 CLV.addLocalVar(pI->getType(), CW.getValueName(pI));
554 /* CLASS CInstPrintVisitor */
556 class CInstPrintVisitor: public InstVisitor<CInstPrintVisitor> {
558 SlotCalculator& Table;
560 const Value *Operand;
562 void outputLValue(Instruction *);
563 void printPhiFromNextBlock(TerminatorInst *tI, int indx);
564 void printIndexingExpr(MemAccessInst *MAI);
567 CInstPrintVisitor (CWriter &cw, SlotCalculator& table, ostream& o)
568 : CW(cw), Table(table), Out(o) {}
570 void visitCastInst(CastInst *I);
571 void visitCallInst(CallInst *I);
572 void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
573 void visitReturnInst(ReturnInst *I);
574 void visitBranchInst(BranchInst *I);
575 void visitSwitchInst(SwitchInst *I);
576 void visitInvokeInst(InvokeInst *I) ;
577 void visitMallocInst(MallocInst *I);
578 void visitAllocaInst(AllocaInst *I);
579 void visitFreeInst(FreeInst *I);
580 void visitLoadInst(LoadInst *I);
581 void visitStoreInst(StoreInst *I);
582 void visitGetElementPtrInst(GetElementPtrInst *I);
583 void visitPHINode(PHINode *I) {}
585 void visitNot(GenericUnaryInst *I);
586 void visitBinaryOperator(Instruction *I);
590 void CInstPrintVisitor::outputLValue(Instruction *I) {
591 Out << " " << CW.getValueName(I) << " = ";
594 void CInstPrintVisitor::printPhiFromNextBlock(TerminatorInst *tI, int indx) {
595 BasicBlock *bb = tI->getSuccessor(indx);
596 BasicBlock::const_iterator insIt = bb->begin();
597 while (insIt != bb->end()) {
598 if (PHINode *pI = dyn_cast<PHINode>(*insIt)) {
600 //Calculate the incoming index for this
601 int incindex = pI->getBasicBlockIndex(tI->getParent());
602 if (incindex != -1) {
603 //now we have to do the printing
605 CW.writeOperand(pI->getIncomingValue(incindex), Out);
614 // Implement all "other" instructions, except for PHINode
615 void CInstPrintVisitor::visitCastInst(CastInst *I) {
617 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
619 CW.printType(I->getType(), Out);
621 CW.writeOperand(Operand, Out);
625 void CInstPrintVisitor::visitCallInst(CallInst *I) {
626 if (I->getType() != Type::VoidTy)
631 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
632 const PointerType *PTy = dyn_cast<PointerType>(Operand->getType());
633 const FunctionType *MTy = PTy
634 ? dyn_cast<FunctionType>(PTy->getElementType()):0;
635 const Type *RetTy = MTy ? MTy->getReturnType() : 0;
637 // If possible, print out the short form of the call instruction, but we can
638 // only do this if the first argument is a pointer to a nonvararg method,
639 // and if the value returned is not a pointer to a method.
641 if (RetTy && !MTy->isVarArg() &&
642 (!isa<PointerType>(RetTy)||
643 !isa<FunctionType>(cast<PointerType>(RetTy)))){
645 Out << makeNameProper(Operand->getName());
647 Out << makeNameProper(Operand->getName());
650 if (I->getNumOperands() > 1)
651 CW.writeOperand(I->getOperand(1), Out);
652 for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
654 CW.writeOperand(I->getOperand(op), Out);
660 // Specific Instruction type classes... note that all of the casts are
661 // neccesary because we use the instruction classes as opaque types...
663 void CInstPrintVisitor::visitReturnInst(ReturnInst *I) {
665 if (I->getNumOperands())
666 CW.writeOperand(I->getOperand(0), Out);
670 void CInstPrintVisitor::visitBranchInst(BranchInst *I) {
671 TerminatorInst *tI = cast<TerminatorInst>(I);
672 if (I->isConditional()) {
674 CW.writeOperand(I->getCondition(), Out);
676 printPhiFromNextBlock(tI,0);
678 CW.writeOperand(I->getOperand(0), Out);
680 Out << " } else {\n";
681 printPhiFromNextBlock(tI,1);
683 CW.writeOperand(I->getOperand(1), Out);
686 printPhiFromNextBlock(tI,0);
688 CW.writeOperand(I->getOperand(0), Out);
694 void CInstPrintVisitor::visitSwitchInst(SwitchInst *I) {
695 assert(0 && "Switch not implemented!");
698 void CInstPrintVisitor::visitInvokeInst(InvokeInst *I) {
699 assert(0 && "Invoke not implemented!");
702 void CInstPrintVisitor::visitMallocInst(MallocInst *I) {
705 CW.printType(I->getType()->getElementType(), Out);
706 Out << "*)malloc(sizeof(";
707 CW.printTypeVar(I->getType()->getElementType(), "");
710 if (I->isArrayAllocation()) {
712 CW.writeOperand(I->getOperand(0), Out);
717 void CInstPrintVisitor::visitAllocaInst(AllocaInst *I) {
719 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
722 CW.printTypeVar(I->getType(), tempstr);
723 Out << ") alloca(sizeof(";
724 CW.printTypeVar(cast<PointerType>(I->getType())->getElementType(),
727 if (I->getNumOperands()) {
729 CW.writeOperand(Operand, Out);
734 void CInstPrintVisitor::visitFreeInst(FreeInst *I) {
735 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
737 CW.writeOperand(Operand, Out);
741 void CInstPrintVisitor::printIndexingExpr(MemAccessInst *MAI) {
742 CW.writeOperand(MAI->getPointerOperand(), Out);
744 for (MemAccessInst::op_iterator I = MAI->idx_begin(), E = MAI->idx_end();
746 if ((*I)->getType() == Type::UIntTy) {
748 CW.writeOperand(*I, Out);
751 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
755 void CInstPrintVisitor::visitLoadInst(LoadInst *I) {
757 printIndexingExpr(I);
761 void CInstPrintVisitor::visitStoreInst(StoreInst *I) {
763 printIndexingExpr(I);
765 CW.writeOperand(I->getOperand(0), Out);
769 void CInstPrintVisitor::visitGetElementPtrInst(GetElementPtrInst *I) {
772 printIndexingExpr(I);
776 void CInstPrintVisitor::visitNot(GenericUnaryInst *I) {
779 CW.writeOperand(I->getOperand(0), Out);
783 void CInstPrintVisitor::visitBinaryOperator(Instruction *I) {
784 // binary instructions, shift instructions, setCond instructions.
786 if (isa<PointerType>(I->getType())) {
788 CW.printType(I->getType(), Out);
792 if (isa<PointerType>(I->getType())) Out << "(long long)";
793 CW.writeOperand(I->getOperand(0), Out);
795 switch (I->getOpcode()) {
796 case Instruction::Add: Out << "+"; break;
797 case Instruction::Sub: Out << "-"; break;
798 case Instruction::Mul: Out << "*"; break;
799 case Instruction::Div: Out << "/"; break;
800 case Instruction::Rem: Out << "%"; break;
801 case Instruction::And: Out << "&"; break;
802 case Instruction::Or: Out << "|"; break;
803 case Instruction::Xor: Out << "^"; break;
804 case Instruction::SetEQ: Out << "=="; break;
805 case Instruction::SetNE: Out << "!="; break;
806 case Instruction::SetLE: Out << "<="; break;
807 case Instruction::SetGE: Out << ">="; break;
808 case Instruction::SetLT: Out << "<"; break;
809 case Instruction::SetGT: Out << ">"; break;
810 case Instruction::Shl : Out << "<<"; break;
811 case Instruction::Shr : Out << ">>"; break;
812 default: cerr << "Invalid operator type!" << I; abort();
815 if (isa<PointerType>(I->getType())) Out << "(long long)";
816 CW.writeOperand(I->getOperand(1), Out);
820 /* END : CInstPrintVisitor implementation */
822 string CWriter::getValueName(const Value *V) {
823 if (V->hasName()) // Print out the label if it exists...
824 return "l_" + makeNameProper(V->getName()) + "_" +
825 utostr(V->getType()->getUniqueID());
827 int Slot = Table.getValSlot(V);
828 assert(Slot >= 0 && "Invalid value!");
829 return "ltmp_" + itostr(Slot) + "_" +
830 utostr(V->getType()->getUniqueID());
833 void CWriter::printModule(const Module *M) {
834 // printing stdlib inclusion
835 // Out << "#include <stdlib.h>\n";
837 // get declaration for alloca
838 Out << "/* Provide Declarations */\n"
839 << "#include <alloca.h>\n\n"
841 // Provide a definition for null if one does not already exist.
842 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
843 << "typedef unsigned char bool;\n"
845 << "\n\n/* Global Symbols */\n";
847 // Loop over the symbol table, emitting all named constants...
848 if (M->hasSymbolTable())
849 printSymbolTable(*M->getSymbolTable());
851 Out << "\n\n/* Global Data */\n";
852 for_each(M->gbegin(), M->gend(),
853 bind_obj(this, &CWriter::printGlobal));
855 // First output all the declarations of the functions as C requires Functions
856 // be declared before they are used.
858 Out << "\n\n/* Function Declarations */\n";
859 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunctionDecl));
861 // Output all of the functions...
862 Out << "\n\n/* Function Bodies */\n";
863 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunction));
866 // prints the global constants
867 void CWriter::printGlobal(const GlobalVariable *GV) {
868 string tempostr = getValueName(GV);
869 if (GV->hasInternalLinkage()) Out << "static ";
871 printTypeVar(GV->getType()->getElementType(), tempostr);
873 if (GV->hasInitializer()) {
875 writeOperand(GV->getInitializer(), Out, false);
881 // printSymbolTable - Run through symbol table looking for named constants
882 // if a named constant is found, emit it's declaration...
883 // Assuming that symbol table has only types and constants.
884 void CWriter::printSymbolTable(const SymbolTable &ST) {
886 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
887 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
888 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
891 // Need to run through all the used types in the program
892 // FindUsedTypes &FUT = new FindUsedTypes();
893 // const std::set<const Type *> &UsedTypes = FUT.getTypes();
894 // Filter out the structures printing forward definitions for each of them
895 // and creating the dependency graph.
896 // Print forward definitions to all of them
897 // print the typedefs topologically sorted
899 // But for now we have
900 for (; I != End; ++I) {
901 const Value *V = I->second;
902 if (const Constant *CPV = dyn_cast<const Constant>(V)) {
904 } else if (const Type *Ty = dyn_cast<const Type>(V)) {
908 tempostr = "llvm__" + I->first;
909 string TypeNameVar = calcTypeNameVar(Ty, TypeNames,
911 Out << TypeNameVar << ";\n";
912 if (!isa<PointerType>(Ty) ||
913 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
914 TypeNames.insert(std::make_pair(Ty, "llvm__"+I->first));
921 // printConstant - Print out a constant pool entry...
923 void CWriter::printConstant(const Constant *CPV) {
925 // Dinakar : Don't know what to do with unnamed constants
926 // should do something about it later.
928 string tempostr = getValueName(CPV);
930 // Print out the constant type...
931 printTypeVar(CPV->getType(), tempostr);
934 // Write the value out now...
935 writeOperand(CPV, Out, false);
940 // printFunctionDecl - Print function declaration
942 void CWriter::printFunctionDecl(const Function *F) {
943 printFunctionSignature(F);
947 void CWriter::printFunctionSignature(const Function *F) {
948 if (F->hasInternalLinkage()) Out << "static ";
950 // Loop over the arguments, printing them...
951 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
953 // Print out the return type and name...
954 printType(F->getReturnType(), Out);
955 Out << " " << makeNameProper(F->getName()) << "(";
957 if (!F->isExternal()) {
958 for_each(F->getArgumentList().begin(), F->getArgumentList().end(),
959 bind_obj(this, &CWriter::printFunctionArgument));
961 // Loop over the arguments, printing them...
962 for (FunctionType::ParamTypes::const_iterator I =
963 FT->getParamTypes().begin(),
964 E = FT->getParamTypes().end(); I != E; ++I) {
965 if (I != FT->getParamTypes().begin()) Out << ", ";
970 // Finish printing arguments...
971 if (FT->isVarArg()) {
972 if (FT->getParamTypes().size()) Out << ", ";
973 Out << "..."; // Output varargs portion of signature!
979 // printFunctionArgument - This member is called for every argument that
980 // is passed into the method. Simply print it out
982 void CWriter::printFunctionArgument(const Argument *Arg) {
983 // Insert commas as we go... the first arg doesn't get a comma
984 if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
987 printTypeVar(Arg->getType(), getValueName(Arg));
990 void CWriter::printFunction(const Function *F) {
991 if (F->isExternal()) return;
993 Table.incorporateFunction(F);
995 // Process each of the basic blocks, gather information and call the
996 // output methods on the CLocalVars and Function* objects.
998 // gather local variable information for each basic block
999 InstLocalVarsVisitor ILV(*this);
1000 ILV.visit((Function *)F);
1002 printFunctionSignature(F);
1005 // Loop over the symbol table, emitting all named constants...
1006 if (F->hasSymbolTable())
1007 printSymbolTable(*F->getSymbolTable());
1009 // print the local variables
1010 // we assume that every local variable is alloca'ed in the C code.
1011 std::map<const Type*, VarListType> &locals = ILV.CLV.LocalVars;
1013 map<const Type*, VarListType>::iterator iter;
1014 for (iter = locals.begin(); iter != locals.end(); ++iter) {
1015 VarListType::iterator listiter;
1016 for (listiter = iter->second.begin(); listiter != iter->second.end();
1019 printTypeVar(iter->first, *listiter);
1024 // print the basic blocks
1025 for_each(F->begin(), F->end(), bind_obj(this, &CWriter::outputBasicBlock));
1028 Table.purgeFunction();
1031 void CWriter::outputBasicBlock(const BasicBlock* BB) {
1032 Out << getValueName(BB) << ":\n";
1034 // Output all of the instructions in the basic block...
1035 // print the basic blocks
1036 CInstPrintVisitor CIPV(*this, Table, Out);
1037 CIPV.visit((BasicBlock *) BB);
1040 // printType - Go to extreme measures to attempt to print out a short, symbolic
1041 // version of a type name.
1042 ostream& CWriter::printType(const Type *Ty, ostream &Out) {
1043 return printTypeInt(Out, Ty, TypeNames);
1047 void CWriter::writeOperand(const Value *Operand,
1048 ostream &Out, bool PrintName = true) {
1049 if (isa<GlobalValue>(Operand))
1050 Out << "(&"; // Global values are references as their addresses by llvm
1052 if (PrintName && Operand->hasName()) {
1053 // If Operand has a name.
1054 Out << "l_" << makeNameProper(Operand->getName()) << "_" <<
1055 Operand->getType()->getUniqueID();
1056 } else if (const Constant *CPV = dyn_cast<const Constant>(Operand)) {
1057 if (isa<ConstantPointerNull>(CPV))
1060 Out << getConstStrValue(CPV);
1062 int Slot = Table.getValSlot(Operand);
1064 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
1069 if (isa<GlobalValue>(Operand))
1074 //===----------------------------------------------------------------------===//
1075 // External Interface declaration
1076 //===----------------------------------------------------------------------===//
1078 void WriteToC(const Module *M, ostream &Out) {
1079 assert(M && "You can't write a null module!!");
1080 SlotCalculator SlotTable(M, false);
1081 CWriter W(Out, SlotTable, M);