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/Instructions.h"
12 #include "llvm/Pass.h"
13 #include "llvm/SymbolTable.h"
14 #include "llvm/Intrinsics.h"
15 #include "llvm/Analysis/FindUsedTypes.h"
16 #include "llvm/Analysis/ConstantsScanner.h"
17 #include "llvm/Support/InstVisitor.h"
18 #include "llvm/Support/InstIterator.h"
19 #include "llvm/Support/CallSite.h"
20 #include "llvm/Support/Mangler.h"
21 #include "Support/StringExtras.h"
22 #include "Support/STLExtras.h"
23 #include "Config/config.h"
28 class CWriter : public Pass, public InstVisitor<CWriter> {
31 const Module *TheModule;
32 std::map<const Type *, std::string> TypeNames;
33 std::set<const Value*> MangledGlobals;
34 bool needsMalloc, emittedInvoke;
36 std::map<const ConstantFP *, unsigned> FPConstantMap;
38 CWriter(std::ostream &o) : Out(o) {}
40 void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequired<FindUsedTypes>();
45 virtual bool run(Module &M) {
49 // Ensure that all structure types have names...
50 bool Changed = nameAllUsedStructureTypes(M);
51 Mang = new Mangler(M);
59 MangledGlobals.clear();
63 std::ostream &printType(std::ostream &Out, const Type *Ty,
64 const std::string &VariableName = "",
65 bool IgnoreName = false, bool namedContext = true);
67 void writeOperand(Value *Operand);
68 void writeOperandInternal(Value *Operand);
71 bool nameAllUsedStructureTypes(Module &M);
72 void printModule(Module *M);
73 void printFloatingPointConstants(Module &M);
74 void printSymbolTable(const SymbolTable &ST);
75 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
76 void printFunctionSignature(const Function *F, bool Prototype);
78 void printFunction(Function *);
80 void printConstant(Constant *CPV);
81 void printConstantArray(ConstantArray *CPA);
83 // isInlinableInst - Attempt to inline instructions into their uses to build
84 // trees as much as possible. To do this, we have to consistently decide
85 // what is acceptable to inline, so that variable declarations don't get
86 // printed and an extra copy of the expr is not emitted.
88 static bool isInlinableInst(const Instruction &I) {
89 // Must be an expression, must be used exactly once. If it is dead, we
90 // emit it inline where it would go.
91 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
92 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
93 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<VANextInst>(I))
94 // Don't inline a load across a store or other bad things!
97 // Only inline instruction it it's use is in the same BB as the inst.
98 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
101 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
102 // variables which are accessed with the & operator. This causes GCC to
103 // generate significantly better code than to emit alloca calls directly.
105 static const AllocaInst *isDirectAlloca(const Value *V) {
106 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
107 if (!AI) return false;
108 if (AI->isArrayAllocation())
109 return 0; // FIXME: we can also inline fixed size array allocas!
110 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
115 // Instruction visitation functions
116 friend class InstVisitor<CWriter>;
118 void visitReturnInst(ReturnInst &I);
119 void visitBranchInst(BranchInst &I);
120 void visitSwitchInst(SwitchInst &I);
121 void visitInvokeInst(InvokeInst &I);
122 void visitUnwindInst(UnwindInst &I);
124 void visitPHINode(PHINode &I);
125 void visitBinaryOperator(Instruction &I);
127 void visitCastInst (CastInst &I);
128 void visitCallInst (CallInst &I);
129 void visitCallSite (CallSite CS);
130 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
132 void visitMallocInst(MallocInst &I);
133 void visitAllocaInst(AllocaInst &I);
134 void visitFreeInst (FreeInst &I);
135 void visitLoadInst (LoadInst &I);
136 void visitStoreInst (StoreInst &I);
137 void visitGetElementPtrInst(GetElementPtrInst &I);
138 void visitVANextInst(VANextInst &I);
139 void visitVAArgInst (VAArgInst &I);
141 void visitInstruction(Instruction &I) {
142 std::cerr << "C Writer does not know about " << I;
146 void outputLValue(Instruction *I) {
147 Out << " " << Mang->getValueName(I) << " = ";
149 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
151 void printIndexingExpression(Value *Ptr, User::op_iterator I,
152 User::op_iterator E);
156 // A pointer type should not use parens around *'s alone, e.g., (**)
157 inline bool ptrTypeNameNeedsParens(const std::string &NameSoFar) {
158 return NameSoFar.find_last_not_of('*') != std::string::npos;
161 // Pass the Type* and the variable name and this prints out the variable
164 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
165 const std::string &NameSoFar,
166 bool IgnoreName, bool namedContext) {
167 if (Ty->isPrimitiveType())
168 switch (Ty->getPrimitiveID()) {
169 case Type::VoidTyID: return Out << "void " << NameSoFar;
170 case Type::BoolTyID: return Out << "bool " << NameSoFar;
171 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
172 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
173 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
174 case Type::ShortTyID: return Out << "short " << NameSoFar;
175 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
176 case Type::IntTyID: return Out << "int " << NameSoFar;
177 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
178 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
179 case Type::FloatTyID: return Out << "float " << NameSoFar;
180 case Type::DoubleTyID: return Out << "double " << NameSoFar;
182 std::cerr << "Unknown primitive type: " << Ty << "\n";
186 // Check to see if the type is named.
187 if (!IgnoreName || isa<OpaqueType>(Ty)) {
188 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
189 if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
192 switch (Ty->getPrimitiveID()) {
193 case Type::FunctionTyID: {
194 const FunctionType *MTy = cast<FunctionType>(Ty);
195 std::stringstream FunctionInnards;
196 FunctionInnards << " (" << NameSoFar << ") (";
197 for (FunctionType::ParamTypes::const_iterator
198 I = MTy->getParamTypes().begin(),
199 E = MTy->getParamTypes().end(); I != E; ++I) {
200 if (I != MTy->getParamTypes().begin())
201 FunctionInnards << ", ";
202 printType(FunctionInnards, *I, "");
204 if (MTy->isVarArg()) {
205 if (!MTy->getParamTypes().empty())
206 FunctionInnards << ", ...";
207 } else if (MTy->getParamTypes().empty()) {
208 FunctionInnards << "void";
210 FunctionInnards << ")";
211 std::string tstr = FunctionInnards.str();
212 printType(Out, MTy->getReturnType(), tstr);
215 case Type::StructTyID: {
216 const StructType *STy = cast<StructType>(Ty);
217 Out << NameSoFar + " {\n";
219 for (StructType::ElementTypes::const_iterator
220 I = STy->getElementTypes().begin(),
221 E = STy->getElementTypes().end(); I != E; ++I) {
223 printType(Out, *I, "field" + utostr(Idx++));
229 case Type::PointerTyID: {
230 const PointerType *PTy = cast<PointerType>(Ty);
231 std::string ptrName = "*" + NameSoFar;
233 // Do not need parens around "* NameSoFar" if NameSoFar consists only
234 // of zero or more '*' chars *and* this is not an unnamed pointer type
235 // such as the result type in a cast statement. Otherwise, enclose in ( ).
236 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
237 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
238 ptrName = "(" + ptrName + ")"; //
240 return printType(Out, PTy->getElementType(), ptrName);
243 case Type::ArrayTyID: {
244 const ArrayType *ATy = cast<ArrayType>(Ty);
245 unsigned NumElements = ATy->getNumElements();
246 return printType(Out, ATy->getElementType(),
247 NameSoFar + "[" + utostr(NumElements) + "]");
250 case Type::OpaqueTyID: {
251 static int Count = 0;
252 std::string TyName = "struct opaque_" + itostr(Count++);
253 assert(TypeNames.find(Ty) == TypeNames.end());
254 TypeNames[Ty] = TyName;
255 return Out << TyName << " " << NameSoFar;
258 assert(0 && "Unhandled case in getTypeProps!");
265 void CWriter::printConstantArray(ConstantArray *CPA) {
267 // As a special case, print the array as a string if it is an array of
268 // ubytes or an array of sbytes with positive values.
270 const Type *ETy = CPA->getType()->getElementType();
271 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
273 // Make sure the last character is a null char, as automatically added by C
274 if (isString && (CPA->getNumOperands() == 0 ||
275 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
280 // Keep track of whether the last number was a hexadecimal escape
281 bool LastWasHex = false;
283 // Do not include the last character, which we know is null
284 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
285 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
287 // Print it out literally if it is a printable character. The only thing
288 // to be careful about is when the last letter output was a hex escape
289 // code, in which case we have to be careful not to print out hex digits
290 // explicitly (the C compiler thinks it is a continuation of the previous
291 // character, sheesh...)
293 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
295 if (C == '"' || C == '\\')
302 case '\n': Out << "\\n"; break;
303 case '\t': Out << "\\t"; break;
304 case '\r': Out << "\\r"; break;
305 case '\v': Out << "\\v"; break;
306 case '\a': Out << "\\a"; break;
307 case '\"': Out << "\\\""; break;
308 case '\'': Out << "\\\'"; break;
311 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
312 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
321 if (CPA->getNumOperands()) {
323 printConstant(cast<Constant>(CPA->getOperand(0)));
324 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
326 printConstant(cast<Constant>(CPA->getOperand(i)));
333 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
334 // textually as a double (rather than as a reference to a stack-allocated
335 // variable). We decide this by converting CFP to a string and back into a
336 // double, and then checking whether the conversion results in a bit-equal
337 // double to the original value of CFP. This depends on us and the target C
338 // compiler agreeing on the conversion process (which is pretty likely since we
339 // only deal in IEEE FP).
341 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
344 sprintf(Buffer, "%a", CFP->getValue());
346 if (!strncmp(Buffer, "0x", 2) ||
347 !strncmp(Buffer, "-0x", 3) ||
348 !strncmp(Buffer, "+0x", 3))
349 return atof(Buffer) == CFP->getValue();
352 std::string StrVal = ftostr(CFP->getValue());
354 while (StrVal[0] == ' ')
355 StrVal.erase(StrVal.begin());
357 // Check to make sure that the stringized number is not some string like "Inf"
358 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
359 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
360 ((StrVal[0] == '-' || StrVal[0] == '+') &&
361 (StrVal[1] >= '0' && StrVal[1] <= '9')))
362 // Reparse stringized version!
363 return atof(StrVal.c_str()) == CFP->getValue();
368 // printConstant - The LLVM Constant to C Constant converter.
369 void CWriter::printConstant(Constant *CPV) {
370 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
371 switch (CE->getOpcode()) {
372 case Instruction::Cast:
374 printType(Out, CPV->getType());
376 printConstant(CE->getOperand(0));
380 case Instruction::GetElementPtr:
382 printIndexingExpression(CE->getOperand(0),
383 CPV->op_begin()+1, CPV->op_end());
386 case Instruction::Add:
387 case Instruction::Sub:
388 case Instruction::Mul:
389 case Instruction::Div:
390 case Instruction::Rem:
391 case Instruction::SetEQ:
392 case Instruction::SetNE:
393 case Instruction::SetLT:
394 case Instruction::SetLE:
395 case Instruction::SetGT:
396 case Instruction::SetGE:
398 printConstant(CE->getOperand(0));
399 switch (CE->getOpcode()) {
400 case Instruction::Add: Out << " + "; break;
401 case Instruction::Sub: Out << " - "; break;
402 case Instruction::Mul: Out << " * "; break;
403 case Instruction::Div: Out << " / "; break;
404 case Instruction::Rem: Out << " % "; break;
405 case Instruction::SetEQ: Out << " == "; break;
406 case Instruction::SetNE: Out << " != "; break;
407 case Instruction::SetLT: Out << " < "; break;
408 case Instruction::SetLE: Out << " <= "; break;
409 case Instruction::SetGT: Out << " > "; break;
410 case Instruction::SetGE: Out << " >= "; break;
411 default: assert(0 && "Illegal opcode here!");
413 printConstant(CE->getOperand(1));
418 std::cerr << "CWriter Error: Unhandled constant expression: "
424 switch (CPV->getType()->getPrimitiveID()) {
426 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
427 case Type::SByteTyID:
428 case Type::ShortTyID:
429 Out << cast<ConstantSInt>(CPV)->getValue(); break;
431 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
432 Out << "((int)0x80000000)"; // Handle MININT specially to avoid warning
434 Out << cast<ConstantSInt>(CPV)->getValue();
438 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
440 case Type::UByteTyID:
441 case Type::UShortTyID:
442 Out << cast<ConstantUInt>(CPV)->getValue(); break;
444 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
445 case Type::ULongTyID:
446 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
448 case Type::FloatTyID:
449 case Type::DoubleTyID: {
450 ConstantFP *FPC = cast<ConstantFP>(CPV);
451 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
452 if (I != FPConstantMap.end()) {
453 // Because of FP precision problems we must load from a stack allocated
454 // value that holds the value in hex.
455 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
456 << "*)&FPConstant" << I->second << ")";
459 // Print out the constant as a floating point number.
461 sprintf(Buffer, "%a", FPC->getValue());
462 Out << Buffer << " /*" << FPC->getValue() << "*/ ";
464 Out << ftostr(FPC->getValue());
470 case Type::ArrayTyID:
471 printConstantArray(cast<ConstantArray>(CPV));
474 case Type::StructTyID: {
476 if (CPV->getNumOperands()) {
478 printConstant(cast<Constant>(CPV->getOperand(0)));
479 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
481 printConstant(cast<Constant>(CPV->getOperand(i)));
488 case Type::PointerTyID:
489 if (isa<ConstantPointerNull>(CPV)) {
491 printType(Out, CPV->getType());
492 Out << ")/*NULL*/0)";
494 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
495 writeOperand(CPR->getValue());
500 std::cerr << "Unknown constant type: " << CPV << "\n";
505 void CWriter::writeOperandInternal(Value *Operand) {
506 if (Instruction *I = dyn_cast<Instruction>(Operand))
507 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
508 // Should we inline this instruction to build a tree?
515 if (Constant *CPV = dyn_cast<Constant>(Operand)) {
518 Out << Mang->getValueName(Operand);
522 void CWriter::writeOperand(Value *Operand) {
523 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
524 Out << "(&"; // Global variables are references as their addresses by llvm
526 writeOperandInternal(Operand);
528 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
532 // nameAllUsedStructureTypes - If there are structure types in the module that
533 // are used but do not have names assigned to them in the symbol table yet then
534 // we assign them names now.
536 bool CWriter::nameAllUsedStructureTypes(Module &M) {
537 // Get a set of types that are used by the program...
538 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
540 // Loop over the module symbol table, removing types from UT that are already
543 SymbolTable &MST = M.getSymbolTable();
544 if (MST.find(Type::TypeTy) != MST.end())
545 for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
546 E = MST.type_end(Type::TypeTy); I != E; ++I)
547 UT.erase(cast<Type>(I->second));
549 // UT now contains types that are not named. Loop over it, naming structure
552 bool Changed = false;
553 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
555 if (const StructType *ST = dyn_cast<StructType>(*I)) {
556 ((Value*)ST)->setName("unnamed", &MST);
562 // generateCompilerSpecificCode - This is where we add conditional compilation
563 // directives to cater to specific compilers as need be.
565 static void generateCompilerSpecificCode(std::ostream& Out) {
566 // Alloca is hard to get, and we don't want to include stdlib.h here...
567 Out << "/* get a declaration for alloca */\n"
569 << "extern void *__builtin_alloca(unsigned long);\n"
570 << "#define alloca(x) __builtin_alloca(x)\n"
572 << "#ifndef __FreeBSD__\n"
573 << "#include <alloca.h>\n"
577 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
578 // If we aren't being compiled with GCC, just drop these attributes.
579 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
580 << "#define __attribute__(X)\n"
584 void CWriter::printModule(Module *M) {
585 // Calculate which global values have names that will collide when we throw
586 // away type information.
587 { // Scope to delete the FoundNames set when we are done with it...
588 std::set<std::string> FoundNames;
589 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
590 if (I->hasName()) // If the global has a name...
591 if (FoundNames.count(I->getName())) // And the name is already used
592 MangledGlobals.insert(I); // Mangle the name
594 FoundNames.insert(I->getName()); // Otherwise, keep track of name
596 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
597 if (I->hasName()) // If the global has a name...
598 if (FoundNames.count(I->getName())) // And the name is already used
599 MangledGlobals.insert(I); // Mangle the name
601 FoundNames.insert(I->getName()); // Otherwise, keep track of name
604 // get declaration for alloca
605 Out << "/* Provide Declarations */\n";
606 Out << "#include <stdarg.h>\n";
607 Out << "#include <setjmp.h>\n";
608 generateCompilerSpecificCode(Out);
610 // Provide a definition for `bool' if not compiling with a C++ compiler.
612 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
614 << "\n\n/* Support for floating point constants */\n"
615 << "typedef unsigned long long ConstantDoubleTy;\n"
616 << "typedef unsigned int ConstantFloatTy;\n"
618 << "\n\n/* Support for the invoke instruction */\n"
619 << "extern struct __llvm_jmpbuf_list_t {\n"
620 << " jmp_buf buf; struct __llvm_jmpbuf_list_t *next;\n"
621 << "} *__llvm_jmpbuf_list;\n"
623 << "\n\n/* Global Declarations */\n";
625 // First output all the declarations for the program, because C requires
626 // Functions & globals to be declared before they are used.
629 // Loop over the symbol table, emitting all named constants...
630 printSymbolTable(M->getSymbolTable());
632 // Global variable declarations...
634 Out << "\n/* External Global Variable Declarations */\n";
635 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
636 if (I->hasExternalLinkage()) {
638 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
644 // Function declarations
646 Out << "\n/* Function Declarations */\n";
648 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
649 // If the function is external and the name collides don't print it.
650 // Sometimes the bytecode likes to have multiple "declarations" for
651 // external functions
652 if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
653 !I->getIntrinsicID()) {
654 printFunctionSignature(I, true);
660 // Print Malloc prototype if needed
662 Out << "\n/* Malloc to make sun happy */\n";
663 Out << "extern void * malloc();\n\n";
666 // Output the global variable declarations
668 Out << "\n\n/* Global Variable Declarations */\n";
669 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
670 if (!I->isExternal()) {
672 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
678 // Output the global variable definitions and contents...
680 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
681 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
682 if (!I->isExternal()) {
683 if (I->hasInternalLinkage())
685 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
686 if (I->hasLinkOnceLinkage())
687 Out << " __attribute__((common))";
688 else if (I->hasWeakLinkage())
689 Out << " __attribute__((weak))";
690 if (!I->getInitializer()->isNullValue()) {
692 writeOperand(I->getInitializer());
698 // Output all floating point constants that cannot be printed accurately...
699 printFloatingPointConstants(*M);
701 // Output all of the functions...
702 emittedInvoke = false;
704 Out << "\n\n/* Function Bodies */\n";
705 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
709 // If the program included an invoke instruction, we need to output the
710 // support code for it here!
712 Out << "\n/* More support for the invoke instruction */\n"
713 << "struct __llvm_jmpbuf_list_t *__llvm_jmpbuf_list "
714 << "__attribute__((common)) = 0;\n";
717 // Done with global FP constants
718 FPConstantMap.clear();
721 /// Output all floating point constants that cannot be printed accurately...
722 void CWriter::printFloatingPointConstants(Module &M) {
725 unsigned long long U;
733 // Scan the module for floating point constants. If any FP constant is used
734 // in the function, we want to redirect it here so that we do not depend on
735 // the precision of the printed form, unless the printed form preserves
738 unsigned FPCounter = 0;
739 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
740 for (constant_iterator I = constant_begin(F), E = constant_end(F);
742 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
743 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
744 !FPConstantMap.count(FPC)) {
745 double Val = FPC->getValue();
747 FPConstantMap[FPC] = FPCounter; // Number the FP constants
749 if (FPC->getType() == Type::DoubleTy) {
751 Out << "const ConstantDoubleTy FPConstant" << FPCounter++
752 << " = 0x" << std::hex << DBLUnion.U << std::dec
753 << "ULL; /* " << Val << " */\n";
754 } else if (FPC->getType() == Type::FloatTy) {
756 Out << "const ConstantFloatTy FPConstant" << FPCounter++
757 << " = 0x" << std::hex << FLTUnion.U << std::dec
758 << "U; /* " << Val << " */\n";
760 assert(0 && "Unknown float type!");
767 /// printSymbolTable - Run through symbol table looking for type names. If a
768 /// type name is found, emit it's declaration...
770 void CWriter::printSymbolTable(const SymbolTable &ST) {
771 // If there are no type names, exit early.
772 if (ST.find(Type::TypeTy) == ST.end())
775 // We are only interested in the type plane of the symbol table...
776 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
777 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
779 // Print out forward declarations for structure types before anything else!
780 Out << "/* Structure forward decls */\n";
781 for (; I != End; ++I)
782 if (const Type *STy = dyn_cast<StructType>(I->second)) {
783 std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
784 Out << Name << ";\n";
785 TypeNames.insert(std::make_pair(STy, Name));
790 // Now we can print out typedefs...
791 Out << "/* Typedefs */\n";
792 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
793 const Type *Ty = cast<Type>(I->second);
794 std::string Name = "l_" + Mangler::makeNameProper(I->first);
796 printType(Out, Ty, Name);
802 // Keep track of which structures have been printed so far...
803 std::set<const StructType *> StructPrinted;
805 // Loop over all structures then push them into the stack so they are
806 // printed in the correct order.
808 Out << "/* Structure contents */\n";
809 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
810 if (const StructType *STy = dyn_cast<StructType>(I->second))
811 printContainedStructs(STy, StructPrinted);
814 // Push the struct onto the stack and recursively push all structs
815 // this one depends on.
816 void CWriter::printContainedStructs(const Type *Ty,
817 std::set<const StructType*> &StructPrinted){
818 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
819 //Check to see if we have already printed this struct
820 if (StructPrinted.count(STy) == 0) {
821 // Print all contained types first...
822 for (StructType::ElementTypes::const_iterator
823 I = STy->getElementTypes().begin(),
824 E = STy->getElementTypes().end(); I != E; ++I) {
825 const Type *Ty1 = I->get();
826 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
827 printContainedStructs(*I, StructPrinted);
830 //Print structure type out..
831 StructPrinted.insert(STy);
832 std::string Name = TypeNames[STy];
833 printType(Out, STy, Name, true);
837 // If it is an array, check contained types and continue
838 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
839 const Type *Ty1 = ATy->getElementType();
840 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
841 printContainedStructs(Ty1, StructPrinted);
846 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
847 // If the program provides its own malloc prototype we don't need
848 // to include the general one.
849 if (Mang->getValueName(F) == "malloc")
852 if (F->hasInternalLinkage()) Out << "static ";
853 if (F->hasLinkOnceLinkage()) Out << "inline ";
855 // Loop over the arguments, printing them...
856 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
858 std::stringstream FunctionInnards;
860 // Print out the name...
861 FunctionInnards << Mang->getValueName(F) << "(";
863 if (!F->isExternal()) {
866 if (F->abegin()->hasName() || !Prototype)
867 ArgName = Mang->getValueName(F->abegin());
868 printType(FunctionInnards, F->afront().getType(), ArgName);
869 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
871 FunctionInnards << ", ";
872 if (I->hasName() || !Prototype)
873 ArgName = Mang->getValueName(I);
876 printType(FunctionInnards, I->getType(), ArgName);
880 // Loop over the arguments, printing them...
881 for (FunctionType::ParamTypes::const_iterator I =
882 FT->getParamTypes().begin(),
883 E = FT->getParamTypes().end(); I != E; ++I) {
884 if (I != FT->getParamTypes().begin()) FunctionInnards << ", ";
885 printType(FunctionInnards, *I);
889 // Finish printing arguments... if this is a vararg function, print the ...,
890 // unless there are no known types, in which case, we just emit ().
892 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
893 if (FT->getParamTypes().size()) FunctionInnards << ", ";
894 FunctionInnards << "..."; // Output varargs portion of signature!
896 FunctionInnards << ")";
897 // Print out the return type and the entire signature for that matter
898 printType(Out, F->getReturnType(), FunctionInnards.str());
900 if (F->hasWeakLinkage()) Out << " __attribute((weak))";
903 void CWriter::printFunction(Function *F) {
904 if (F->isExternal()) return;
906 printFunctionSignature(F, false);
909 // print local variable information for the function
910 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
911 if (const AllocaInst *AI = isDirectAlloca(*I)) {
913 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
914 Out << "; /* Address exposed local */\n";
915 } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
917 printType(Out, (*I)->getType(), Mang->getValueName(*I));
920 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
922 printType(Out, (*I)->getType(),
923 Mang->getValueName(*I)+"__PHI_TEMPORARY");
930 // print the basic blocks
931 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
932 BasicBlock *Prev = BB->getPrev();
934 // Don't print the label for the basic block if there are no uses, or if the
935 // only terminator use is the predecessor basic block's terminator. We have
936 // to scan the use list because PHI nodes use basic blocks too but do not
937 // require a label to be generated.
939 bool NeedsLabel = false;
940 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
942 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
943 if (TI != Prev->getTerminator() ||
944 isa<SwitchInst>(Prev->getTerminator()) ||
945 isa<InvokeInst>(Prev->getTerminator())) {
950 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
952 // Output all of the instructions in the basic block...
953 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
954 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
955 if (II->getType() != Type::VoidTy)
964 // Don't emit prefix or suffix for the terminator...
965 visit(*BB->getTerminator());
971 // Specific Instruction type classes... note that all of the casts are
972 // necessary because we use the instruction classes as opaque types...
974 void CWriter::visitReturnInst(ReturnInst &I) {
975 // Don't output a void return if this is the last basic block in the function
976 if (I.getNumOperands() == 0 &&
977 &*--I.getParent()->getParent()->end() == I.getParent() &&
978 !I.getParent()->size() == 1) {
983 if (I.getNumOperands()) {
985 writeOperand(I.getOperand(0));
990 void CWriter::visitSwitchInst(SwitchInst &SI) {
992 writeOperand(SI.getOperand(0));
993 Out << ") {\n default:\n";
994 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
996 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
998 writeOperand(SI.getOperand(i));
1000 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1001 printBranchToBlock(SI.getParent(), Succ, 2);
1002 if (Succ == SI.getParent()->getNext())
1008 void CWriter::visitInvokeInst(InvokeInst &II) {
1010 << " struct __llvm_jmpbuf_list_t Entry;\n"
1011 << " Entry.next = __llvm_jmpbuf_list;\n"
1012 << " if (setjmp(Entry.buf)) {\n"
1013 << " __llvm_jmpbuf_list = Entry.next;\n";
1014 printBranchToBlock(II.getParent(), II.getExceptionalDest(), 4);
1016 << " __llvm_jmpbuf_list = &Entry;\n"
1019 if (II.getType() != Type::VoidTy) outputLValue(&II);
1022 << " __llvm_jmpbuf_list = Entry.next;\n"
1024 printBranchToBlock(II.getParent(), II.getNormalDest(), 0);
1025 emittedInvoke = true;
1029 void CWriter::visitUnwindInst(UnwindInst &I) {
1030 // The unwind instructions causes a control flow transfer out of the current
1031 // function, unwinding the stack until a caller who used the invoke
1032 // instruction is found. In this context, we code generated the invoke
1033 // instruction to add an entry to the top of the jmpbuf_list. Thus, here we
1034 // just have to longjmp to the specified handler.
1035 Out << " if (__llvm_jmpbuf_list == 0) { /* unwind */\n"
1036 << " extern write();\n"
1037 << " ((void (*)(int, void*, unsigned))write)(2,\n"
1038 << " \"throw found with no handler!\\n\", 31); abort();\n"
1040 << " longjmp(__llvm_jmpbuf_list->buf, 1);\n";
1041 emittedInvoke = true;
1044 static bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1045 // If PHI nodes need copies, we need the copy code...
1046 if (isa<PHINode>(To->front()) ||
1047 From->getNext() != To) // Not directly successor, need goto
1050 // Otherwise we don't need the code.
1054 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1056 for (BasicBlock::iterator I = Succ->begin();
1057 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1058 // now we have to do the printing
1059 Out << std::string(Indent, ' ');
1060 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1061 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
1062 Out << "; /* for PHI node */\n";
1065 if (CurBB->getNext() != Succ ||
1066 isa<InvokeInst>(CurBB->getTerminator()) ||
1067 isa<SwitchInst>(CurBB->getTerminator())) {
1068 Out << std::string(Indent, ' ') << " goto ";
1074 // Branch instruction printing - Avoid printing out a branch to a basic block
1075 // that immediately succeeds the current one.
1077 void CWriter::visitBranchInst(BranchInst &I) {
1078 if (I.isConditional()) {
1079 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1081 writeOperand(I.getCondition());
1084 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1086 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1087 Out << " } else {\n";
1088 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1091 // First goto not necessary, assume second one is...
1093 writeOperand(I.getCondition());
1096 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1101 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1106 // PHI nodes get copied into temporary values at the end of predecessor basic
1107 // blocks. We now need to copy these temporary values into the REAL value for
1109 void CWriter::visitPHINode(PHINode &I) {
1111 Out << "__PHI_TEMPORARY";
1115 void CWriter::visitBinaryOperator(Instruction &I) {
1116 // binary instructions, shift instructions, setCond instructions.
1117 assert(!isa<PointerType>(I.getType()));
1119 // We must cast the results of binary operations which might be promoted.
1120 bool needsCast = false;
1121 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1122 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1123 || (I.getType() == Type::FloatTy)) {
1126 printType(Out, I.getType(), "", false, false);
1130 writeOperand(I.getOperand(0));
1132 switch (I.getOpcode()) {
1133 case Instruction::Add: Out << " + "; break;
1134 case Instruction::Sub: Out << " - "; break;
1135 case Instruction::Mul: Out << "*"; break;
1136 case Instruction::Div: Out << "/"; break;
1137 case Instruction::Rem: Out << "%"; break;
1138 case Instruction::And: Out << " & "; break;
1139 case Instruction::Or: Out << " | "; break;
1140 case Instruction::Xor: Out << " ^ "; break;
1141 case Instruction::SetEQ: Out << " == "; break;
1142 case Instruction::SetNE: Out << " != "; break;
1143 case Instruction::SetLE: Out << " <= "; break;
1144 case Instruction::SetGE: Out << " >= "; break;
1145 case Instruction::SetLT: Out << " < "; break;
1146 case Instruction::SetGT: Out << " > "; break;
1147 case Instruction::Shl : Out << " << "; break;
1148 case Instruction::Shr : Out << " >> "; break;
1149 default: std::cerr << "Invalid operator type!" << I; abort();
1152 writeOperand(I.getOperand(1));
1159 void CWriter::visitCastInst(CastInst &I) {
1160 if (I.getType() == Type::BoolTy) {
1162 writeOperand(I.getOperand(0));
1167 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1169 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1170 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1171 // Avoid "cast to pointer from integer of different size" warnings
1175 writeOperand(I.getOperand(0));
1178 void CWriter::visitCallInst(CallInst &I) {
1179 // Handle intrinsic function calls first...
1180 if (Function *F = I.getCalledFunction())
1181 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1183 default: assert(0 && "Unknown LLVM intrinsic!");
1184 case LLVMIntrinsic::va_start:
1187 Out << "va_start(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1188 // Output the last argument to the enclosing function...
1189 writeOperand(&I.getParent()->getParent()->aback());
1192 case LLVMIntrinsic::va_end:
1193 Out << "va_end(*(va_list*)&";
1194 writeOperand(I.getOperand(1));
1197 case LLVMIntrinsic::va_copy:
1199 Out << "va_copy(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1200 Out << "*(va_list*)&";
1201 writeOperand(I.getOperand(1));
1204 case LLVMIntrinsic::setjmp:
1205 case LLVMIntrinsic::sigsetjmp:
1206 // This intrinsic should never exist in the program, but until we get
1207 // setjmp/longjmp transformations going on, we should codegen it to
1208 // something reasonable. This will allow code that never calls longjmp
1212 case LLVMIntrinsic::longjmp:
1213 case LLVMIntrinsic::siglongjmp:
1214 // Longjmp is not implemented, and never will be. It would cause an
1223 void CWriter::visitCallSite(CallSite CS) {
1224 const PointerType *PTy = cast<PointerType>(CS.getCalledValue()->getType());
1225 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1226 const Type *RetTy = FTy->getReturnType();
1228 writeOperand(CS.getCalledValue());
1231 if (CS.arg_begin() != CS.arg_end()) {
1232 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1235 for (++AI; AI != AE; ++AI) {
1243 void CWriter::visitMallocInst(MallocInst &I) {
1245 printType(Out, I.getType());
1246 Out << ")malloc(sizeof(";
1247 printType(Out, I.getType()->getElementType());
1250 if (I.isArrayAllocation()) {
1252 writeOperand(I.getOperand(0));
1257 void CWriter::visitAllocaInst(AllocaInst &I) {
1259 printType(Out, I.getType());
1260 Out << ") alloca(sizeof(";
1261 printType(Out, I.getType()->getElementType());
1263 if (I.isArrayAllocation()) {
1265 writeOperand(I.getOperand(0));
1270 void CWriter::visitFreeInst(FreeInst &I) {
1271 Out << "free((char*)";
1272 writeOperand(I.getOperand(0));
1276 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1277 User::op_iterator E) {
1278 bool HasImplicitAddress = false;
1279 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1280 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1281 HasImplicitAddress = true;
1282 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1283 HasImplicitAddress = true;
1284 Ptr = CPR->getValue(); // Get to the global...
1285 } else if (isDirectAlloca(Ptr)) {
1286 HasImplicitAddress = true;
1290 if (!HasImplicitAddress)
1291 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1293 writeOperandInternal(Ptr);
1297 const Constant *CI = dyn_cast<Constant>(I);
1298 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1301 writeOperandInternal(Ptr);
1303 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1305 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1308 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1309 "Can only have implicit address with direct accessing");
1311 if (HasImplicitAddress) {
1313 } else if (CI && CI->isNullValue() && I+1 != E) {
1314 // Print out the -> operator if possible...
1315 if ((*(I+1))->getType() == Type::UByteTy) {
1316 Out << (HasImplicitAddress ? "." : "->");
1317 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1323 if ((*I)->getType() == Type::LongTy) {
1328 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1332 void CWriter::visitLoadInst(LoadInst &I) {
1334 writeOperand(I.getOperand(0));
1337 void CWriter::visitStoreInst(StoreInst &I) {
1339 writeOperand(I.getPointerOperand());
1341 writeOperand(I.getOperand(0));
1344 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1346 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1349 void CWriter::visitVANextInst(VANextInst &I) {
1350 Out << Mang->getValueName(I.getOperand(0));
1351 Out << "; va_arg(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1352 printType(Out, I.getArgType(), "", /*ignoreName*/false,
1353 /*namedContext*/false);
1357 void CWriter::visitVAArgInst(VAArgInst &I) {
1359 Out << "{ va_list Tmp; va_copy(Tmp, *(va_list*)&";
1360 writeOperand(I.getOperand(0));
1361 Out << ");\n " << Mang->getValueName(&I) << " = va_arg(Tmp, ";
1362 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1363 Out << ");\n va_end(Tmp); }";
1367 //===----------------------------------------------------------------------===//
1368 // External Interface declaration
1369 //===----------------------------------------------------------------------===//
1371 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }