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/Module.h"
14 #include "llvm/Argument.h"
15 #include "llvm/Function.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/GlobalVariable.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/SymbolTable.h"
25 #include "llvm/Support/InstVisitor.h"
26 #include "Support/StringExtras.h"
27 #include "Support/STLExtras.h"
36 //===-----------------------------------------------------------------------==//
38 // Implementation of the CLocalVars methods
40 // Appends a variable to the LocalVars map if it does not already exist
41 // Also check that the type exists on the map.
42 void CLocalVars::addLocalVar(const Type *t, const string & var) {
43 if (!LocalVars.count(t) ||
44 find(LocalVars[t].begin(), LocalVars[t].end(), var)
45 == LocalVars[t].end()) {
46 LocalVars[t].push_back(var);
50 static string calcTypeNameVar(const Type *Ty,
51 map<const Type *, string> &TypeNames,
52 string VariableName, string NameSoFar);
54 static std::string getConstStrValue(const Constant* CPV);
58 //Getting opcodes in terms of the operator
60 static const char *getOpcodeOperName(const Instruction *I) {
61 switch (I->getOpcode()) {
62 // Standard binary operators...
63 case Instruction::Add: return "+";
64 case Instruction::Sub: return "-";
65 case Instruction::Mul: return "*";
66 case Instruction::Div: return "/";
67 case Instruction::Rem: return "%";
69 // Logical operators...
70 case Instruction::And: return "&";
71 case Instruction::Or: return "|";
72 case Instruction::Xor: return "^";
74 // SetCond operators...
75 case Instruction::SetEQ: return "==";
76 case Instruction::SetNE: return "!=";
77 case Instruction::SetLE: return "<=";
78 case Instruction::SetGE: return ">=";
79 case Instruction::SetLT: return "<";
80 case Instruction::SetGT: return ">";
84 case Instruction::Shl : return "<<";
85 case Instruction::Shr : return ">>";
88 cerr << "Invalid operator type!" << I->getOpcode() << "\n";
95 // We dont want identifier names with ., space, - in them.
96 // So we replace them with _
97 static string makeNameProper(string x) {
99 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++) {
112 static string getConstantName(const Constant *CPV) {
113 return CPV->getName();
117 static std::string getConstArrayStrValue(const Constant* CPV) {
120 // As a special case, print the array as a string if it is an array of
121 // ubytes or an array of sbytes with positive values.
123 const Type *ETy = cast<ArrayType>(CPV->getType())->getElementType();
124 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
126 if (ETy == Type::SByteTy) {
127 for (unsigned i = 0; i < CPV->getNumOperands(); ++i)
128 if (ETy == Type::SByteTy &&
129 cast<ConstantSInt>(CPV->getOperand(i))->getValue() < 0) {
137 for (unsigned i = 0; i < CPV->getNumOperands(); ++i) {
138 unsigned char C = (ETy == Type::SByteTy) ?
139 (unsigned char)cast<ConstantSInt>(CPV->getOperand(i))->getValue() :
140 (unsigned char)cast<ConstantUInt>(CPV->getOperand(i))->getValue();
146 Result += ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
147 Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
154 if (CPV->getNumOperands()) {
155 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
156 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
157 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
165 static std::string getConstStructStrValue(const Constant* CPV) {
166 std::string Result = "{";
167 if (CPV->getNumOperands()) {
168 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
169 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
170 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
173 return Result + " }";
176 // our own getStrValue function for constant initializers
177 static std::string getConstStrValue(const Constant* CPV) {
178 // Does not handle null pointers, that needs to be checked explicitly
180 if (CPV == ConstantBool::False)
182 else if (CPV == ConstantBool::True)
185 else if (isa<ConstantArray>(CPV)) {
186 tempstr = getConstArrayStrValue(CPV);
188 else if (isa<ConstantStruct>(CPV)) {
189 tempstr = getConstStructStrValue(CPV);
191 else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(CPV)) {
192 tempstr = utostr(CUI->getValue());
194 else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CPV)) {
195 tempstr = itostr(CSI->getValue());
197 else if (ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
198 tempstr = ftostr(CFP->getValue());
201 if (CPV->getType() == Type::ULongTy)
203 else if (CPV->getType() == Type::LongTy)
205 else if (CPV->getType() == Type::UIntTy ||
206 CPV->getType() == Type::UShortTy)
214 // Essentially pass the Type* variable, an empty typestack and this prints
216 static string calcTypeName(const Type *Ty, map<const Type *, string> &TypeNames,
217 string &FunctionInfo) {
219 // Takin' care of the fact that boolean would be int in C
220 // and that ushort would be unsigned short etc.
223 if (Ty->isPrimitiveType())
224 switch (Ty->getPrimitiveID()) {
225 case Type::VoidTyID: return "void";
226 case Type::BoolTyID: return "bool";
227 case Type::UByteTyID: return "unsigned char";
228 case Type::SByteTyID: return "signed char";
229 case Type::UShortTyID: return "unsigned short";
230 case Type::ShortTyID: return "short";
231 case Type::UIntTyID: return "unsigned";
232 case Type::IntTyID: return "int";
233 case Type::ULongTyID: return "unsigned long long";
234 case Type::LongTyID: return "signed long long";
235 case Type::FloatTyID: return "float";
236 case Type::DoubleTyID: return "double";
237 default : assert(0 && "Unknown primitive type!");
240 // Check to see if the type is named.
241 map<const Type *, string>::iterator I = TypeNames.find(Ty);
242 if (I != TypeNames.end())
247 switch (Ty->getPrimitiveID()) {
248 case Type::FunctionTyID: {
249 const FunctionType *MTy = cast<const FunctionType>(Ty);
250 Result = calcTypeName(MTy->getReturnType(), TypeNames, MInfo);
252 Result += ") " + MInfo;
254 FunctionInfo += " (";
255 for (FunctionType::ParamTypes::const_iterator
256 I = MTy->getParamTypes().begin(),
257 E = MTy->getParamTypes().end(); I != E; ++I) {
258 if (I != MTy->getParamTypes().begin())
259 FunctionInfo += ", ";
261 FunctionInfo += calcTypeName(*I, TypeNames, MInfo);
263 Result += ") " + MInfo;
265 if (MTy->isVarArg()) {
266 if (!MTy->getParamTypes().empty())
267 FunctionInfo += ", ";
268 FunctionInfo += "...";
273 case Type::StructTyID: {
275 const StructType *STy = cast<const StructType>(Ty);
276 Result = " struct {\n ";
278 for (StructType::ElementTypes::const_iterator
279 I = STy->getElementTypes().begin(),
280 E = STy->getElementTypes().end(); I != E; ++I) {
281 Result += calcTypeNameVar(*I, TypeNames,
282 "field" + itostr(indx++), tempstr);
288 case Type::PointerTyID:
289 Result = calcTypeName(cast<const PointerType>(Ty)->getElementType(),
293 case Type::ArrayTyID: {
294 const ArrayType *ATy = cast<const ArrayType>(Ty);
295 int NumElements = ATy->getNumElements();
296 Result = calcTypeName(ATy->getElementType(), TypeNames, MInfo);
301 assert(0 && "Unhandled case in getTypeProps!");
309 // Pass the Type* variable and and the variable name and this prints out the
310 // variable declaration.
311 // This is different from calcTypeName because if you need to declare an array
312 // the size of the array would appear after the variable name itself
313 // For eg. int a[10];
314 static string calcTypeNameVar(const Type *Ty,
315 map<const Type *, string> &TypeNames,
316 string VariableName, string NameSoFar) {
317 if (Ty->isPrimitiveType())
318 switch (Ty->getPrimitiveID()) {
320 return "bool " + NameSoFar + VariableName;
321 case Type::UByteTyID:
322 return "unsigned char " + NameSoFar + VariableName;
323 case Type::SByteTyID:
324 return "signed char " + NameSoFar + VariableName;
325 case Type::UShortTyID:
326 return "unsigned long long " + NameSoFar + VariableName;
327 case Type::ULongTyID:
328 return "unsigned long long " + NameSoFar + VariableName;
330 return "signed long long " + NameSoFar + VariableName;
332 return "unsigned " + NameSoFar + VariableName;
334 return Ty->getDescription() + " " + NameSoFar + VariableName;
337 // Check to see if the type is named.
338 map<const Type *, string>::iterator I = TypeNames.find(Ty);
339 if (I != TypeNames.end())
340 return I->second + " " + NameSoFar + VariableName;
345 switch (Ty->getPrimitiveID()) {
346 case Type::FunctionTyID: {
348 const FunctionType *MTy = cast<const FunctionType>(Ty);
349 Result += calcTypeName(MTy->getReturnType(), TypeNames, MInfo);
351 Result += ") " + MInfo;
352 Result += " " + NameSoFar + VariableName;
354 for (FunctionType::ParamTypes::const_iterator
355 I = MTy->getParamTypes().begin(),
356 E = MTy->getParamTypes().end(); I != E; ++I) {
357 if (I != MTy->getParamTypes().begin())
360 Result += calcTypeName(*I, TypeNames, MInfo);
362 Result += ") " + MInfo;
364 if (MTy->isVarArg()) {
365 if (!MTy->getParamTypes().empty())
372 case Type::StructTyID: {
373 const StructType *STy = cast<const StructType>(Ty);
374 Result = " struct {\n ";
376 for (StructType::ElementTypes::const_iterator
377 I = STy->getElementTypes().begin(),
378 E = STy->getElementTypes().end(); I != E; ++I) {
379 Result += calcTypeNameVar(*I, TypeNames,
380 "field" + itostr(indx++), "");
384 Result += " " + NameSoFar + VariableName;
388 case Type::PointerTyID: {
389 Result = calcTypeNameVar(cast<const PointerType>(Ty)->getElementType(),
391 "(*" + NameSoFar + VariableName + ")");
395 case Type::ArrayTyID: {
396 const ArrayType *ATy = cast<const ArrayType>(Ty);
397 int NumElements = ATy->getNumElements();
398 Result = calcTypeNameVar(ATy->getElementType(), TypeNames,
399 tempstr, NameSoFar + VariableName + "[" +
400 itostr(NumElements) + "]");
404 assert(0 && "Unhandled case in getTypeProps!");
411 // printTypeVarInt - The internal guts of printing out a type that has a
412 // potentially named portion and the variable associated with the type.
413 static ostream &printTypeVarInt(ostream &Out, const Type *Ty,
414 map<const Type *, string> &TypeNames,
415 const string &VariableName) {
416 // Primitive types always print out their description, regardless of whether
417 // they have been named or not.
419 if (Ty->isPrimitiveType())
420 switch (Ty->getPrimitiveID()) {
422 return Out << "bool " << VariableName;
423 case Type::UByteTyID:
424 return Out << "unsigned char " << VariableName;
425 case Type::SByteTyID:
426 return Out << "signed char " << VariableName;
427 case Type::UShortTyID:
428 return Out << "unsigned long long " << VariableName;
429 case Type::ULongTyID:
430 return Out << "unsigned long long " << VariableName;
432 return Out << "signed long long " << VariableName;
434 return Out << "unsigned " << VariableName;
436 return Out << Ty->getDescription() << " " << VariableName;
439 // Check to see if the type is named.
440 map<const Type *, string>::iterator I = TypeNames.find(Ty);
441 if (I != TypeNames.end()) return Out << I->second << " " << VariableName;
443 // Otherwise we have a type that has not been named but is a derived type.
444 // Carefully recurse the type hierarchy to print out any contained symbolic
447 string TypeNameVar, tempstr = "";
448 TypeNameVar = calcTypeNameVar(Ty, TypeNames, VariableName, tempstr);
449 return Out << TypeNameVar;
452 // Internal guts of printing a type name
453 static ostream &printTypeInt(ostream &Out, const Type *Ty,
454 map<const Type *, string> &TypeNames) {
455 // Primitive types always print out their description, regardless of whether
456 // they have been named or not.
458 if (Ty->isPrimitiveType())
459 switch (Ty->getPrimitiveID()) {
461 return Out << "bool";
462 case Type::UByteTyID:
463 return Out << "unsigned char";
464 case Type::SByteTyID:
465 return Out << "signed char";
466 case Type::UShortTyID:
467 return Out << "unsigned short";
468 case Type::ULongTyID:
469 return Out << "unsigned long long";
471 return Out << "signed long long";
473 return Out << "unsigned";
475 return Out << Ty->getDescription();
478 // Check to see if the type is named.
479 map<const Type *, string>::iterator I = TypeNames.find(Ty);
480 if (I != TypeNames.end()) return Out << I->second;
482 // Otherwise we have a type that has not been named but is a derived type.
483 // Carefully recurse the type hierarchy to print out any contained symbolic
487 string TypeName = calcTypeName(Ty, TypeNames, MInfo);
488 // TypeNames.insert(std::make_pair(Ty, TypeName));
489 //Cache type name for later use
491 return Out << TypeName << ")" << MInfo;
493 return Out << TypeName;
498 //Internal CWriter class mimics AssemblyWriter.
501 SlotCalculator &Table;
502 const Module *TheModule;
503 map<const Type *, string> TypeNames;
505 inline CWriter(ostream &o, SlotCalculator &Tab, const Module *M)
506 : Out(o), Table(Tab), TheModule(M) {
509 inline void write(const Module *M) { printModule(M); }
511 ostream& printTypeVar(const Type *Ty, const string &VariableName) {
512 return printTypeVarInt(Out, Ty, TypeNames, VariableName);
517 ostream& printType(const Type *Ty, ostream &Out);
518 void writeOperand(const Value *Operand, ostream &Out,bool PrintName = true);
520 string getValueName(const Value *V);
523 void printModule(const Module *M);
524 void printSymbolTable(const SymbolTable &ST);
525 void printConstant(const Constant *CPV);
526 void printGlobal(const GlobalVariable *GV);
527 void printFunctionSignature(const Function *F);
528 void printFunctionDecl(const Function *F); // Print just the forward decl
529 void printFunctionArgument(const Argument *FA);
531 void printFunction(const Function *);
533 void outputBasicBlock(const BasicBlock *);
535 /* END class CWriter */
538 /* CLASS InstLocalVarsVisitor */
539 class InstLocalVarsVisitor : public InstVisitor<InstLocalVarsVisitor> {
541 void handleTerminator(TerminatorInst *tI, int indx);
545 InstLocalVarsVisitor(CWriter &cw) : CW(cw) {}
547 void visitInstruction(Instruction *I) {
548 if (I->getType() != Type::VoidTy) {
549 string tempostr = CW.getValueName(I);
550 CLV.addLocalVar(I->getType(), tempostr);
554 void visitBranchInst(BranchInst *I) {
555 handleTerminator(I, 0);
556 if (I->isConditional())
557 handleTerminator(I, 1);
562 void InstLocalVarsVisitor::handleTerminator(TerminatorInst *tI,int indx) {
563 BasicBlock *bb = tI->getSuccessor(indx);
565 BasicBlock::const_iterator insIt = bb->begin();
566 while (insIt != bb->end()) {
567 if (const PHINode *pI = dyn_cast<PHINode>(*insIt)) {
569 // Calculate the incoming index for this
570 assert(pI->getBasicBlockIndex(tI->getParent()) != -1);
572 CLV.addLocalVar(pI->getType(), CW.getValueName(pI));
580 /* CLASS CInstPrintVisitor */
582 class CInstPrintVisitor: public InstVisitor<CInstPrintVisitor> {
584 SlotCalculator& Table;
586 const Value *Operand;
588 void outputLValue(Instruction *);
589 void printPhiFromNextBlock(TerminatorInst *tI, int indx);
592 CInstPrintVisitor (CWriter &cw, SlotCalculator& table, ostream& o)
593 : CW(cw), Table(table), Out(o) {
597 void visitCastInst(CastInst *I);
598 void visitCallInst(CallInst *I);
599 void visitShr(ShiftInst *I);
600 void visitShl(ShiftInst *I);
601 void visitReturnInst(ReturnInst *I);
602 void visitBranchInst(BranchInst *I);
603 void visitSwitchInst(SwitchInst *I);
604 void visitInvokeInst(InvokeInst *I) ;
605 void visitMallocInst(MallocInst *I);
606 void visitAllocaInst(AllocaInst *I);
607 void visitFreeInst(FreeInst *I);
608 void visitLoadInst(LoadInst *I);
609 void visitStoreInst(StoreInst *I);
610 void visitGetElementPtrInst(GetElementPtrInst *I);
611 void visitPHINode(PHINode *I);
612 void visitUnaryOperator (UnaryOperator *I);
613 void visitBinaryOperator(BinaryOperator *I);
617 void CInstPrintVisitor::outputLValue(Instruction *I) {
618 Out << " " << CW.getValueName(I) << " = ";
621 void CInstPrintVisitor::printPhiFromNextBlock(TerminatorInst *tI, int indx) {
622 BasicBlock *bb = tI->getSuccessor(indx);
623 BasicBlock::const_iterator insIt = bb->begin();
624 while (insIt != bb->end()) {
625 if (PHINode *pI = dyn_cast<PHINode>(*insIt)) {
627 //Calculate the incoming index for this
628 int incindex = pI->getBasicBlockIndex(tI->getParent());
629 if (incindex != -1) {
630 //now we have to do the printing
632 CW.writeOperand(pI->getIncomingValue(incindex), Out);
641 // Implement all "other" instructions, except for PHINode
642 void CInstPrintVisitor::visitCastInst(CastInst *I) {
644 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
646 CW.printType(I->getType(), Out);
648 CW.writeOperand(Operand, Out);
652 void CInstPrintVisitor::visitCallInst(CallInst *I) {
654 if (I->getType() != Type::VoidTy)
657 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
658 const PointerType *PTy = dyn_cast<PointerType>(Operand->getType());
659 const FunctionType *MTy = PTy
660 ? dyn_cast<FunctionType>(PTy->getElementType()):0;
661 const Type *RetTy = MTy ? MTy->getReturnType() : 0;
663 // If possible, print out the short form of the call instruction, but we can
664 // only do this if the first argument is a pointer to a nonvararg method,
665 // and if the value returned is not a pointer to a method.
667 if (RetTy && !MTy->isVarArg() &&
668 (!isa<PointerType>(RetTy)||
669 !isa<FunctionType>(cast<PointerType>(RetTy)))){
671 Out << makeNameProper(Operand->getName());
673 Out << makeNameProper(Operand->getName());
676 if (I->getNumOperands() > 1)
677 CW.writeOperand(I->getOperand(1), Out);
678 for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
680 CW.writeOperand(I->getOperand(op), Out);
686 void CInstPrintVisitor::visitShr(ShiftInst *I) {
688 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
690 CW.writeOperand(Operand, Out);
693 CW.writeOperand(I->getOperand(1), Out);
697 void CInstPrintVisitor::visitShl(ShiftInst *I) {
699 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
701 CW.writeOperand(Operand, Out);
704 CW.writeOperand(I->getOperand(1), Out);
708 // Specific Instruction type classes... note that all of the casts are
709 // neccesary because we use the instruction classes as opaque types...
711 void CInstPrintVisitor::visitReturnInst(ReturnInst *I) {
713 if (I->getNumOperands())
714 CW.writeOperand(I->getOperand(0), Out);
718 void CInstPrintVisitor::visitBranchInst(BranchInst *I) {
719 TerminatorInst *tI = cast<TerminatorInst>(I);
720 if (I->isConditional()) {
722 CW.writeOperand(I->getCondition(), Out);
724 printPhiFromNextBlock(tI,0);
726 CW.writeOperand(I->getOperand(0), Out);
729 printPhiFromNextBlock(tI,1);
731 CW.writeOperand(I->getOperand(1), Out);
734 printPhiFromNextBlock(tI,0);
736 CW.writeOperand(I->getOperand(0), Out);
742 void CInstPrintVisitor::visitSwitchInst(SwitchInst *I) {
743 assert(0 && "Switch not implemented!");
746 void CInstPrintVisitor::visitInvokeInst(InvokeInst *I) {
747 assert(0 && "Invoke not implemented!");
750 void CInstPrintVisitor::visitMallocInst(MallocInst *I) {
752 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
755 CW.printType(cast<PointerType>(I->getType())->getElementType(), Out);
756 Out << "*) malloc(sizeof(";
757 CW.printTypeVar(cast<PointerType>(I->getType())->getElementType(),
760 if (I->getNumOperands()) {
762 CW.writeOperand(Operand, Out);
767 void CInstPrintVisitor::visitAllocaInst(AllocaInst *I) {
769 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
772 CW.printTypeVar(I->getType(), tempstr);
773 Out << ") alloca(sizeof(";
774 CW.printTypeVar(cast<PointerType>(I->getType())->getElementType(),
777 if (I->getNumOperands()) {
779 CW.writeOperand(Operand, Out);
784 void CInstPrintVisitor::visitFreeInst(FreeInst *I) {
785 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
787 CW.writeOperand(Operand, Out);
791 void CInstPrintVisitor::visitLoadInst(LoadInst *I) {
793 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
794 if (I->getNumOperands() <= 1) {
796 CW.writeOperand(Operand, Out);
799 //Check if it is an array type or struct type ptr!
801 const PointerType *PTy = dyn_cast<PointerType>(I->getType());
802 if (cast<const PointerType>(Operand->getType())->getElementType()->getPrimitiveID() == Type::StructTyID)
804 if (arrtype && isa<GlobalValue>(Operand))
806 CW.writeOperand(Operand,Out);
807 for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
809 if (arrtype || !isa<GlobalValue>(Operand)) {
811 CW.writeOperand(I->getOperand(i), Out);
814 if (isa<GlobalValue>(Operand) && arrtype)
818 if (arrtype == 1) Out << "[";
821 CW.writeOperand(I->getOperand(i), Out);
822 if (arrtype == 1) Out << "]";
829 void CInstPrintVisitor::visitStoreInst(StoreInst *I) {
830 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
831 if (I->getNumOperands() <= 2) {
833 CW.writeOperand(I->getOperand(1), Out);
836 //Check if it is an array type or struct type ptr!
838 if (cast<const PointerType>(I->getOperand(1)->getType())->getElementType()->getPrimitiveID() == Type::StructTyID)
840 if (isa<GlobalValue>(I->getOperand(1)) && arrtype)
842 CW.writeOperand(I->getOperand(1), Out);
843 for (unsigned i = 2, E = I->getNumOperands(); i != E; ++i) {
845 if (arrtype || !isa<GlobalValue>(I->getOperand(1))) {
847 CW.writeOperand(I->getOperand(i), Out);
850 if (isa<GlobalValue>(I->getOperand(1)) && arrtype)
854 if (arrtype == 1) Out << "[";
857 CW.writeOperand(I->getOperand(i), Out);
858 if (arrtype == 1) Out << "]";
863 CW.writeOperand(Operand, Out);
867 void CInstPrintVisitor::visitGetElementPtrInst(GetElementPtrInst *I) {
869 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
871 if (I->getNumOperands() <= 1)
872 CW.writeOperand(Operand, Out);
874 //Check if it is an array type or struct type ptr!
876 if ((cast<const PointerType>(Operand->getType()))->getElementType()->getPrimitiveID() == Type::StructTyID)
878 if ((isa<GlobalValue>(Operand)) && arrtype)
880 CW.writeOperand(Operand, Out);
881 for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
883 if (arrtype || !isa<GlobalValue>(Operand)){
885 CW.writeOperand(I->getOperand(i), Out);
888 if (isa<GlobalValue>(Operand) && arrtype)
892 if (arrtype == 1) Out << "[";
895 CW.writeOperand(I->getOperand(i), Out);
896 if (arrtype == 1) Out << "]";
903 void CInstPrintVisitor::visitPHINode(PHINode *I) {
907 void CInstPrintVisitor::visitUnaryOperator (UnaryOperator *I) {
908 if (I->getOpcode() == Instruction::Not) {
910 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
912 CW.writeOperand(Operand, Out);
916 Out << "<bad unary inst>\n";
920 void CInstPrintVisitor::visitBinaryOperator(BinaryOperator *I) {
921 //binary instructions, shift instructions, setCond instructions.
923 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
924 if (I->getType()->getPrimitiveID() == Type::PointerTyID) {
926 CW.printType(I->getType(), Out);
930 if (Operand->getType()->getPrimitiveID() == Type::PointerTyID)
931 Out << "(long long)";
932 CW.writeOperand(Operand, Out);
933 Out << getOpcodeOperName(I);
934 // Need the extra parenthisis if the second operand is < 0
936 if (I->getOperand(1)->getType()->getPrimitiveID() == Type::PointerTyID)
937 Out << "(long long)";
938 CW.writeOperand(I->getOperand(1), Out);
943 /* END : CInstPrintVisitor implementation */
945 string CWriter::getValueName(const Value *V) {
946 if (V->hasName()) // Print out the label if it exists...
947 return "llvm__" + makeNameProper(V->getName()) + "_" +
948 utostr(V->getType()->getUniqueID());
950 int Slot = Table.getValSlot(V);
951 assert(Slot >= 0 && "Invalid value!");
952 return "llvm__tmp_" + itostr(Slot) + "_" +
953 utostr(V->getType()->getUniqueID());
956 void CWriter::printModule(const Module *M) {
957 // printing stdlib inclusion
958 // Out << "#include <stdlib.h>\n";
960 // get declaration for alloca
961 Out << "/* Provide Declarations */\n"
962 << "#include <alloca.h>\n\n"
964 // Provide a definition for null if one does not already exist.
965 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
966 << "typedef unsigned char bool;\n"
968 << "\n\n/* Global Symbols */\n";
970 // Loop over the symbol table, emitting all named constants...
971 if (M->hasSymbolTable())
972 printSymbolTable(*M->getSymbolTable());
974 Out << "\n\n/* Global Data */\n";
975 for_each(M->gbegin(), M->gend(),
976 bind_obj(this, &CWriter::printGlobal));
978 // First output all the declarations of the functions as C requires Functions
979 // be declared before they are used.
981 Out << "\n\n/* Function Declarations */\n";
982 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunctionDecl));
984 // Output all of the functions...
985 Out << "\n\n/* Function Bodies */\n";
986 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunction));
989 // prints the global constants
990 void CWriter::printGlobal(const GlobalVariable *GV) {
991 string tempostr = getValueName(GV);
992 if (GV->hasInternalLinkage()) Out << "static ";
994 printTypeVar(GV->getType()->getElementType(), tempostr);
996 if (GV->hasInitializer()) {
998 writeOperand(GV->getInitializer(), Out, false);
1004 // printSymbolTable - Run through symbol table looking for named constants
1005 // if a named constant is found, emit it's declaration...
1006 // Assuming that symbol table has only types and constants.
1007 void CWriter::printSymbolTable(const SymbolTable &ST) {
1009 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
1010 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
1011 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
1014 // Need to run through all the used types in the program
1015 // FindUsedTypes &FUT = new FindUsedTypes();
1016 // const std::set<const Type *> &UsedTypes = FUT.getTypes();
1017 // Filter out the structures printing forward definitions for each of them
1018 // and creating the dependency graph.
1019 // Print forward definitions to all of them
1020 // print the typedefs topologically sorted
1022 // But for now we have
1023 for (; I != End; ++I) {
1024 const Value *V = I->second;
1025 if (const Constant *CPV = dyn_cast<const Constant>(V)) {
1027 } else if (const Type *Ty = dyn_cast<const Type>(V)) {
1029 string tempstr = "";
1031 tempostr = "llvm__" + I->first;
1032 string TypeNameVar = calcTypeNameVar(Ty, TypeNames,
1034 Out << TypeNameVar << ";\n";
1035 if (!isa<PointerType>(Ty) ||
1036 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
1037 TypeNames.insert(std::make_pair(Ty, "llvm__"+I->first));
1044 // printConstant - Print out a constant pool entry...
1046 void CWriter::printConstant(const Constant *CPV) {
1048 // Dinakar : Don't know what to do with unnamed constants
1049 // should do something about it later.
1051 string tempostr = getValueName(CPV);
1053 // Print out the constant type...
1054 printTypeVar(CPV->getType(), tempostr);
1057 // Write the value out now...
1058 writeOperand(CPV, Out, false);
1063 // printFunctionDecl - Print function declaration
1065 void CWriter::printFunctionDecl(const Function *F) {
1066 printFunctionSignature(F);
1070 void CWriter::printFunctionSignature(const Function *F) {
1071 if (F->hasInternalLinkage()) Out << "static ";
1073 // Loop over the arguments, printing them...
1074 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1076 // Print out the return type and name...
1077 printType(F->getReturnType(), Out);
1078 Out << " " << makeNameProper(F->getName()) << "(";
1080 if (!F->isExternal()) {
1081 for_each(F->getArgumentList().begin(), F->getArgumentList().end(),
1082 bind_obj(this, &CWriter::printFunctionArgument));
1084 // Loop over the arguments, printing them...
1085 for (FunctionType::ParamTypes::const_iterator I =
1086 FT->getParamTypes().begin(),
1087 E = FT->getParamTypes().end(); I != E; ++I) {
1088 if (I != FT->getParamTypes().begin()) Out << ", ";
1093 // Finish printing arguments...
1094 if (FT->isVarArg()) {
1095 if (FT->getParamTypes().size()) Out << ", ";
1096 Out << "..."; // Output varargs portion of signature!
1102 // printFunctionArgument - This member is called for every argument that
1103 // is passed into the method. Simply print it out
1105 void CWriter::printFunctionArgument(const Argument *Arg) {
1106 // Insert commas as we go... the first arg doesn't get a comma
1107 if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
1110 printTypeVar(Arg->getType(), getValueName(Arg));
1113 void CWriter::printFunction(const Function *F) {
1114 if (F->isExternal()) return;
1116 Table.incorporateFunction(F);
1118 // Process each of the basic blocks, gather information and call the
1119 // output methods on the CLocalVars and Function* objects.
1121 // gather local variable information for each basic block
1122 InstLocalVarsVisitor ILV(*this);
1123 ILV.visit((Function *)F);
1125 printFunctionSignature(F);
1128 // Loop over the symbol table, emitting all named constants...
1129 if (F->hasSymbolTable())
1130 printSymbolTable(*F->getSymbolTable());
1132 // print the local variables
1133 // we assume that every local variable is alloca'ed in the C code.
1134 std::map<const Type*, VarListType> &locals = ILV.CLV.LocalVars;
1136 map<const Type*, VarListType>::iterator iter;
1137 for (iter = locals.begin(); iter != locals.end(); ++iter) {
1138 VarListType::iterator listiter;
1139 for (listiter = iter->second.begin(); listiter != iter->second.end();
1142 printTypeVar(iter->first, *listiter);
1147 // print the basic blocks
1148 for_each(F->begin(), F->end(), bind_obj(this, &CWriter::outputBasicBlock));
1151 Table.purgeFunction();
1154 void CWriter::outputBasicBlock(const BasicBlock* BB) {
1155 Out << getValueName(BB) << ":\n";
1157 // Output all of the instructions in the basic block...
1158 // print the basic blocks
1159 CInstPrintVisitor CIPV(*this, Table, Out);
1160 CIPV.visit((BasicBlock *) BB);
1163 // printType - Go to extreme measures to attempt to print out a short, symbolic
1164 // version of a type name.
1165 ostream& CWriter::printType(const Type *Ty, ostream &Out) {
1166 return printTypeInt(Out, Ty, TypeNames);
1170 void CWriter::writeOperand(const Value *Operand,
1171 ostream &Out, bool PrintName = true) {
1172 if (PrintName && Operand->hasName()) {
1173 // If Operand has a name.
1174 Out << "llvm__" << makeNameProper(Operand->getName()) << "_" <<
1175 Operand->getType()->getUniqueID();
1178 else if (const Constant *CPV = dyn_cast<const Constant>(Operand)) {
1179 if (isa<ConstantPointerNull>(CPV))
1182 Out << getConstStrValue(CPV);
1185 int Slot = Table.getValSlot(Operand);
1187 Out << "llvm__tmp_" << Slot << "_" << Operand->getType()->getUniqueID();
1194 //===----------------------------------------------------------------------===//
1195 // External Interface declaration
1196 //===----------------------------------------------------------------------===//
1198 void WriteToC(const Module *M, ostream &Out) {
1199 assert(M && "You can't write a null module!!");
1200 SlotCalculator SlotTable(M, false);
1201 CWriter W(Out, SlotTable, M);