1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
3 // This library implements the functionality defined in llvm/Assembly/CWriter.h
5 // TODO : Recursive types.
7 //===-----------------------------------------------------------------------==//
9 #include "llvm/Assembly/CWriter.h"
10 #include "llvm/Constants.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/Module.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/iTerminators.h"
15 #include "llvm/iPHINode.h"
16 #include "llvm/iOther.h"
17 #include "llvm/iOperators.h"
18 #include "llvm/SymbolTable.h"
19 #include "llvm/SlotCalculator.h"
20 #include "llvm/Support/InstVisitor.h"
21 #include "llvm/Support/InstIterator.h"
22 #include "Support/StringExtras.h"
23 #include "Support/STLExtras.h"
31 class CWriter : public InstVisitor<CWriter> {
33 SlotCalculator &Table;
34 const Module *TheModule;
35 map<const Type *, string> TypeNames;
36 std::set<const Value*> MangledGlobals;
38 inline CWriter(ostream &o, SlotCalculator &Tab, const Module *M)
39 : Out(o), Table(Tab), TheModule(M) {
42 inline void write(Module *M) { printModule(M); }
44 ostream &printType(const Type *Ty, const string &VariableName = "",
45 bool IgnoreName = false, bool namedContext = true);
47 void writeOperand(Value *Operand);
48 void writeOperandInternal(Value *Operand);
50 string getValueName(const Value *V);
53 void printModule(Module *M);
54 void printSymbolTable(const SymbolTable &ST);
55 void printGlobal(const GlobalVariable *GV);
56 void printFunctionSignature(const Function *F, bool Prototype);
58 void printFunction(Function *);
60 void printConstant(Constant *CPV);
61 void printConstantArray(ConstantArray *CPA);
63 // isInlinableInst - Attempt to inline instructions into their uses to build
64 // trees as much as possible. To do this, we have to consistently decide
65 // what is acceptable to inline, so that variable declarations don't get
66 // printed and an extra copy of the expr is not emitted.
68 static bool isInlinableInst(const Instruction &I) {
69 // Must be an expression, must be used exactly once. If it is dead, we
70 // emit it inline where it would go.
71 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
72 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I))
75 // Only inline instruction it it's use is in the same BB as the inst.
76 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
79 // Instruction visitation functions
80 friend class InstVisitor<CWriter>;
82 void visitReturnInst(ReturnInst &I);
83 void visitBranchInst(BranchInst &I);
85 void visitPHINode(PHINode &I) {}
86 void visitBinaryOperator(Instruction &I);
88 void visitCastInst (CastInst &I);
89 void visitCallInst (CallInst &I);
90 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
92 void visitMallocInst(MallocInst &I);
93 void visitAllocaInst(AllocaInst &I);
94 void visitFreeInst (FreeInst &I);
95 void visitLoadInst (LoadInst &I);
96 void visitStoreInst (StoreInst &I);
97 void visitGetElementPtrInst(GetElementPtrInst &I);
99 void visitInstruction(Instruction &I) {
100 std::cerr << "C Writer does not know about " << I;
104 void outputLValue(Instruction *I) {
105 Out << " " << getValueName(I) << " = ";
107 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
109 void printIndexingExpression(Value *Ptr, User::op_iterator I,
110 User::op_iterator E);
114 // We dont want identifier names with ., space, - in them.
115 // So we replace them with _
116 static string makeNameProper(string x) {
118 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
120 case '.': tmp += "d_"; break;
121 case ' ': tmp += "s_"; break;
122 case '-': tmp += "D_"; break;
129 string CWriter::getValueName(const Value *V) {
130 if (V->hasName()) { // Print out the label if it exists...
131 if (isa<GlobalValue>(V) && // Do not mangle globals...
132 cast<GlobalValue>(V)->hasExternalLinkage() && // Unless it's internal or
133 !MangledGlobals.count(V)) // Unless the name would collide if we don't
134 return makeNameProper(V->getName());
136 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
137 makeNameProper(V->getName());
140 int Slot = Table.getValSlot(V);
141 assert(Slot >= 0 && "Invalid value!");
142 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
145 // A pointer type should not use parens around *'s alone, e.g., (**)
146 inline bool ptrTypeNameNeedsParens(const string &NameSoFar) {
147 return (NameSoFar.find_last_not_of('*') != std::string::npos);
150 // Pass the Type* and the variable name and this prints out the variable
153 ostream &CWriter::printType(const Type *Ty, const string &NameSoFar,
154 bool IgnoreName, bool namedContext) {
155 if (Ty->isPrimitiveType())
156 switch (Ty->getPrimitiveID()) {
157 case Type::VoidTyID: return Out << "void " << NameSoFar;
158 case Type::BoolTyID: return Out << "bool " << NameSoFar;
159 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
160 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
161 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
162 case Type::ShortTyID: return Out << "short " << NameSoFar;
163 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
164 case Type::IntTyID: return Out << "int " << NameSoFar;
165 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
166 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
167 case Type::FloatTyID: return Out << "float " << NameSoFar;
168 case Type::DoubleTyID: return Out << "double " << NameSoFar;
170 std::cerr << "Unknown primitive type: " << Ty << "\n";
174 // Check to see if the type is named.
176 map<const Type *, string>::iterator I = TypeNames.find(Ty);
177 if (I != TypeNames.end()) {
178 return Out << I->second << " " << NameSoFar;
182 switch (Ty->getPrimitiveID()) {
183 case Type::FunctionTyID: {
184 const FunctionType *MTy = cast<FunctionType>(Ty);
185 printType(MTy->getReturnType(), "");
186 Out << " " << NameSoFar << " (";
188 for (FunctionType::ParamTypes::const_iterator
189 I = MTy->getParamTypes().begin(),
190 E = MTy->getParamTypes().end(); I != E; ++I) {
191 if (I != MTy->getParamTypes().begin())
195 if (MTy->isVarArg()) {
196 if (!MTy->getParamTypes().empty())
202 case Type::StructTyID: {
203 const StructType *STy = cast<StructType>(Ty);
204 Out << NameSoFar + " {\n";
206 for (StructType::ElementTypes::const_iterator
207 I = STy->getElementTypes().begin(),
208 E = STy->getElementTypes().end(); I != E; ++I) {
210 printType(*I, "field" + utostr(Idx++));
216 case Type::PointerTyID: {
217 const PointerType *PTy = cast<PointerType>(Ty);
218 std::string ptrName = "*" + NameSoFar;
220 // Do not need parens around "* NameSoFar" if NameSoFar consists only
221 // of zero or more '*' chars *and* this is not an unnamed pointer type
222 // such as the result type in a cast statement. Otherwise, enclose in ( ).
223 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext)
224 ptrName = "(" + ptrName + ")"; //
226 return printType(PTy->getElementType(), ptrName);
229 case Type::ArrayTyID: {
230 const ArrayType *ATy = cast<ArrayType>(Ty);
231 unsigned NumElements = ATy->getNumElements();
232 return printType(ATy->getElementType(),
233 NameSoFar + "[" + utostr(NumElements) + "]");
236 assert(0 && "Unhandled case in getTypeProps!");
243 void CWriter::printConstantArray(ConstantArray *CPA) {
245 // As a special case, print the array as a string if it is an array of
246 // ubytes or an array of sbytes with positive values.
248 const Type *ETy = CPA->getType()->getElementType();
249 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
251 // Make sure the last character is a null char, as automatically added by C
252 if (CPA->getNumOperands() == 0 ||
253 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
258 // Do not include the last character, which we know is null
259 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
260 unsigned char C = (ETy == Type::SByteTy) ?
261 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
262 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
268 case '\n': Out << "\\n"; break;
269 case '\t': Out << "\\t"; break;
270 case '\r': Out << "\\r"; break;
271 case '\v': Out << "\\v"; break;
272 case '\a': Out << "\\a"; break;
275 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
276 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
284 if (CPA->getNumOperands()) {
286 printConstant(cast<Constant>(CPA->getOperand(0)));
287 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
289 printConstant(cast<Constant>(CPA->getOperand(i)));
297 // printConstant - The LLVM Constant to C Constant converter.
298 void CWriter::printConstant(Constant *CPV) {
299 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
300 switch (CE->getOpcode()) {
301 case Instruction::Cast:
303 printType(CPV->getType());
305 printConstant(cast<Constant>(CPV->getOperand(0)));
309 case Instruction::GetElementPtr:
311 printIndexingExpression(CPV->getOperand(0),
312 CPV->op_begin()+1, CPV->op_end());
315 case Instruction::Add:
317 printConstant(cast<Constant>(CPV->getOperand(0)));
319 printConstant(cast<Constant>(CPV->getOperand(1)));
322 case Instruction::Sub:
324 printConstant(cast<Constant>(CPV->getOperand(0)));
326 printConstant(cast<Constant>(CPV->getOperand(1)));
331 std::cerr << "CWriter Error: Unhandled constant expression: "
337 switch (CPV->getType()->getPrimitiveID()) {
339 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
340 case Type::SByteTyID:
341 case Type::ShortTyID:
343 Out << cast<ConstantSInt>(CPV)->getValue(); break;
345 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
347 case Type::UByteTyID:
348 case Type::UShortTyID:
349 Out << cast<ConstantUInt>(CPV)->getValue(); break;
351 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
352 case Type::ULongTyID:
353 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
355 case Type::FloatTyID:
356 case Type::DoubleTyID:
357 Out << cast<ConstantFP>(CPV)->getValue(); break;
359 case Type::ArrayTyID:
360 printConstantArray(cast<ConstantArray>(CPV));
363 case Type::StructTyID: {
365 if (CPV->getNumOperands()) {
367 printConstant(cast<Constant>(CPV->getOperand(0)));
368 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
370 printConstant(cast<Constant>(CPV->getOperand(i)));
377 case Type::PointerTyID:
378 if (isa<ConstantPointerNull>(CPV)) {
380 printType(CPV->getType(), "");
383 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
384 writeOperand(CPR->getValue());
389 std::cerr << "Unknown constant type: " << CPV << "\n";
394 void CWriter::writeOperandInternal(Value *Operand) {
395 if (Instruction *I = dyn_cast<Instruction>(Operand))
396 if (isInlinableInst(*I)) {
397 // Should we inline this instruction to build a tree?
404 if (Operand->hasName()) {
405 Out << getValueName(Operand);
406 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
409 int Slot = Table.getValSlot(Operand);
410 assert(Slot >= 0 && "Malformed LLVM!");
411 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
415 void CWriter::writeOperand(Value *Operand) {
416 if (isa<GlobalVariable>(Operand))
417 Out << "(&"; // Global variables are references as their addresses by llvm
419 writeOperandInternal(Operand);
421 if (isa<GlobalVariable>(Operand))
425 void CWriter::printModule(Module *M) {
426 // Calculate which global values have names that will collide when we throw
427 // away type information.
428 { // Scope to delete the FoundNames set when we are done with it...
429 std::set<string> FoundNames;
430 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
431 if (I->hasName()) // If the global has a name...
432 if (FoundNames.count(I->getName())) // And the name is already used
433 MangledGlobals.insert(I); // Mangle the name
435 FoundNames.insert(I->getName()); // Otherwise, keep track of name
437 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
438 if (I->hasName()) // If the global has a name...
439 if (FoundNames.count(I->getName())) // And the name is already used
440 MangledGlobals.insert(I); // Mangle the name
442 FoundNames.insert(I->getName()); // Otherwise, keep track of name
446 // printing stdlib inclusion
447 // Out << "#include <stdlib.h>\n";
449 // get declaration for alloca
450 Out << "/* Provide Declarations */\n"
451 << "#include <malloc.h>\n"
452 << "#include <alloca.h>\n\n"
454 // Provide a definition for null if one does not already exist,
455 // and for `bool' if not compiling with a C++ compiler.
456 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
457 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
459 << "\n\n/* Global Declarations */\n";
461 // First output all the declarations for the program, because C requires
462 // Functions & globals to be declared before they are used.
465 // Loop over the symbol table, emitting all named constants...
466 if (M->hasSymbolTable())
467 printSymbolTable(*M->getSymbolTable());
469 // Global variable declarations...
471 Out << "\n/* Global Variable Declarations */\n";
472 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
473 Out << (I->hasExternalLinkage() ? "extern " : "static ");
474 printType(I->getType()->getElementType(), getValueName(I));
479 // Function declarations
481 Out << "\n/* Function Declarations */\n";
482 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
483 printFunctionSignature(I, true);
488 // Output the global variable contents...
490 Out << "\n\n/* Global Data */\n";
491 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
492 if (I->hasInternalLinkage()) Out << "static ";
493 printType(I->getType()->getElementType(), getValueName(I));
495 if (I->hasInitializer()) {
497 writeOperand(I->getInitializer());
503 // Output all of the functions...
505 Out << "\n\n/* Function Bodies */\n";
506 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
512 // printSymbolTable - Run through symbol table looking for named constants
513 // if a named constant is found, emit it's declaration...
514 // Assuming that symbol table has only types and constants.
515 void CWriter::printSymbolTable(const SymbolTable &ST) {
516 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
517 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
518 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
520 for (; I != End; ++I)
521 if (const Type *Ty = dyn_cast<StructType>(I->second)) {
522 string Name = "struct l_" + makeNameProper(I->first);
523 Out << Name << ";\n";
524 TypeNames.insert(std::make_pair(Ty, Name));
530 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
531 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
532 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
534 for (; I != End; ++I) {
535 const Value *V = I->second;
536 if (const Type *Ty = dyn_cast<Type>(V)) {
537 string Name = "l_" + makeNameProper(I->first);
538 if (isa<StructType>(Ty))
539 Name = "struct " + makeNameProper(Name);
543 printType(Ty, Name, true);
551 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
552 if (F->hasInternalLinkage()) Out << "static ";
554 // Loop over the arguments, printing them...
555 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
557 // Print out the return type and name...
558 printType(F->getReturnType());
559 Out << getValueName(F) << "(";
561 if (!F->isExternal()) {
564 if (F->abegin()->hasName() || !Prototype)
565 ArgName = getValueName(F->abegin());
567 printType(F->afront().getType(), ArgName);
569 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
572 if (I->hasName() || !Prototype)
573 ArgName = getValueName(I);
576 printType(I->getType(), ArgName);
580 // Loop over the arguments, printing them...
581 for (FunctionType::ParamTypes::const_iterator I =
582 FT->getParamTypes().begin(),
583 E = FT->getParamTypes().end(); I != E; ++I) {
584 if (I != FT->getParamTypes().begin()) Out << ", ";
589 // Finish printing arguments...
590 if (FT->isVarArg()) {
591 if (FT->getParamTypes().size()) Out << ", ";
592 Out << "..."; // Output varargs portion of signature!
598 void CWriter::printFunction(Function *F) {
599 if (F->isExternal()) return;
601 Table.incorporateFunction(F);
603 printFunctionSignature(F, false);
606 // print local variable information for the function
607 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
608 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
610 printType((*I)->getType(), getValueName(*I));
614 // print the basic blocks
615 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
616 BasicBlock *Prev = BB->getPrev();
618 // Don't print the label for the basic block if there are no uses, or if the
619 // only terminator use is the precessor basic block's terminator. We have
620 // to scan the use list because PHI nodes use basic blocks too but do not
621 // require a label to be generated.
623 bool NeedsLabel = false;
624 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
626 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
627 if (TI != Prev->getTerminator()) {
632 if (NeedsLabel) Out << getValueName(BB) << ":\n";
634 // Output all of the instructions in the basic block...
635 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
636 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
637 if (II->getType() != Type::VoidTy)
646 // Don't emit prefix or suffix for the terminator...
647 visit(*BB->getTerminator());
651 Table.purgeFunction();
654 // Specific Instruction type classes... note that all of the casts are
655 // neccesary because we use the instruction classes as opaque types...
657 void CWriter::visitReturnInst(ReturnInst &I) {
658 // Don't output a void return if this is the last basic block in the function
659 if (I.getNumOperands() == 0 &&
660 &*--I.getParent()->getParent()->end() == I.getParent() &&
661 !I.getParent()->size() == 1) {
666 if (I.getNumOperands()) {
668 writeOperand(I.getOperand(0));
673 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
674 // If PHI nodes need copies, we need the copy code...
675 if (isa<PHINode>(To->front()) ||
676 From->getNext() != To) // Not directly successor, need goto
679 // Otherwise we don't need the code.
683 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
685 for (BasicBlock::iterator I = Succ->begin();
686 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
687 // now we have to do the printing
688 Out << string(Indent, ' ');
690 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
691 Out << "; /* for PHI node */\n";
694 if (CurBB->getNext() != Succ) {
695 Out << string(Indent, ' ') << " goto ";
701 // Brach instruction printing - Avoid printing out a brach to a basic block that
702 // immediately succeeds the current one.
704 void CWriter::visitBranchInst(BranchInst &I) {
705 if (I.isConditional()) {
706 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
708 writeOperand(I.getCondition());
711 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
713 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
714 Out << " } else {\n";
715 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
718 // First goto not neccesary, assume second one is...
720 writeOperand(I.getCondition());
723 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
728 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
734 void CWriter::visitBinaryOperator(Instruction &I) {
735 // binary instructions, shift instructions, setCond instructions.
736 if (isa<PointerType>(I.getType())) {
738 printType(I.getType());
742 if (isa<PointerType>(I.getType())) Out << "(long long)";
743 writeOperand(I.getOperand(0));
745 switch (I.getOpcode()) {
746 case Instruction::Add: Out << " + "; break;
747 case Instruction::Sub: Out << " - "; break;
748 case Instruction::Mul: Out << "*"; break;
749 case Instruction::Div: Out << "/"; break;
750 case Instruction::Rem: Out << "%"; break;
751 case Instruction::And: Out << " & "; break;
752 case Instruction::Or: Out << " | "; break;
753 case Instruction::Xor: Out << " ^ "; break;
754 case Instruction::SetEQ: Out << " == "; break;
755 case Instruction::SetNE: Out << " != "; break;
756 case Instruction::SetLE: Out << " <= "; break;
757 case Instruction::SetGE: Out << " >= "; break;
758 case Instruction::SetLT: Out << " < "; break;
759 case Instruction::SetGT: Out << " > "; break;
760 case Instruction::Shl : Out << " << "; break;
761 case Instruction::Shr : Out << " >> "; break;
762 default: std::cerr << "Invalid operator type!" << I; abort();
765 if (isa<PointerType>(I.getType())) Out << "(long long)";
766 writeOperand(I.getOperand(1));
769 void CWriter::visitCastInst(CastInst &I) {
771 printType(I.getType(), string(""),/*ignoreName*/false, /*namedContext*/false);
773 writeOperand(I.getOperand(0));
776 void CWriter::visitCallInst(CallInst &I) {
777 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
778 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
779 const Type *RetTy = FTy->getReturnType();
781 Out << getValueName(I.getOperand(0)) << "(";
783 if (I.getNumOperands() > 1) {
784 writeOperand(I.getOperand(1));
786 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
788 writeOperand(I.getOperand(op));
794 void CWriter::visitMallocInst(MallocInst &I) {
796 printType(I.getType());
797 Out << ")malloc(sizeof(";
798 printType(I.getType()->getElementType());
801 if (I.isArrayAllocation()) {
803 writeOperand(I.getOperand(0));
808 void CWriter::visitAllocaInst(AllocaInst &I) {
810 printType(I.getType());
811 Out << ") alloca(sizeof(";
812 printType(I.getType()->getElementType());
814 if (I.isArrayAllocation()) {
816 writeOperand(I.getOperand(0));
821 void CWriter::visitFreeInst(FreeInst &I) {
823 writeOperand(I.getOperand(0));
827 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
828 User::op_iterator E) {
829 bool HasImplicitAddress = false;
830 // If accessing a global value with no indexing, avoid *(&GV) syndrome
831 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
832 HasImplicitAddress = true;
833 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
834 HasImplicitAddress = true;
835 Ptr = CPR->getValue(); // Get to the global...
839 if (!HasImplicitAddress)
840 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
842 writeOperandInternal(Ptr);
846 const Constant *CI = dyn_cast<Constant>(I->get());
847 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
850 writeOperandInternal(Ptr);
852 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
855 // Print out the -> operator if possible...
856 if (CI && CI->isNullValue() && I+1 != E) {
857 if ((*(I+1))->getType() == Type::UByteTy) {
858 Out << (HasImplicitAddress ? "." : "->");
859 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
861 } else { // First array index of 0: Just skip it
867 if ((*I)->getType() == Type::UIntTy) {
868 Out << "[((int) ("; // sign-extend from 32 (to 64) bits
871 printType(cast<PointerType>(Ptr->getType())->getElementType());
872 Out << "))) / sizeof(";
873 printType(cast<PointerType>(Ptr->getType())->getElementType());
876 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
880 void CWriter::visitLoadInst(LoadInst &I) {
882 writeOperand(I.getOperand(0));
885 void CWriter::visitStoreInst(StoreInst &I) {
887 writeOperand(I.getPointerOperand());
889 writeOperand(I.getOperand(0));
892 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
894 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
897 //===----------------------------------------------------------------------===//
898 // External Interface declaration
899 //===----------------------------------------------------------------------===//
901 void WriteToC(const Module *M, ostream &Out) {
902 assert(M && "You can't write a null module!!");
903 SlotCalculator SlotTable(M, false);
904 CWriter W(Out, SlotTable, M);