1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library converts LLVM code to C code, compilable by GCC and other C
13 //===----------------------------------------------------------------------===//
15 #include "CTargetMachine.h"
16 #include "llvm/Target/TargetMachineImpls.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/SymbolTable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicLowering.h"
26 #include "llvm/Analysis/FindUsedTypes.h"
27 #include "llvm/Analysis/ConstantsScanner.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/Support/CallSite.h"
30 #include "llvm/Support/GetElementPtrTypeIterator.h"
31 #include "llvm/Support/InstVisitor.h"
32 #include "llvm/Support/Mangler.h"
33 #include "Support/StringExtras.h"
34 #include "Config/config.h"
40 class CWriter : public Pass, public InstVisitor<CWriter> {
42 IntrinsicLowering &IL;
44 const Module *TheModule;
47 std::map<const Type *, std::string> TypeNames;
49 std::map<const ConstantFP *, unsigned> FPConstantMap;
51 CWriter(std::ostream &o, IntrinsicLowering &il) : Out(o), IL(il) {}
53 void getAnalysisUsage(AnalysisUsage &AU) const {
54 AU.addRequired<FindUsedTypes>();
57 virtual const char *getPassName() const { return "C backend"; }
59 bool doInitialization(Module &M);
61 // First pass, lower all unhandled intrinsics.
66 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
76 std::ostream &printType(std::ostream &Out, const Type *Ty,
77 const std::string &VariableName = "",
78 bool IgnoreName = false);
80 void writeOperand(Value *Operand);
81 void writeOperandInternal(Value *Operand);
84 void lowerIntrinsics(Module &M);
86 bool nameAllUsedStructureTypes(Module &M);
87 void printModule(Module *M);
88 void printFloatingPointConstants(Module &M);
89 void printSymbolTable(const SymbolTable &ST);
90 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
91 void printFunctionSignature(const Function *F, bool Prototype);
93 void printFunction(Function &);
95 void printConstant(Constant *CPV);
96 void printConstantArray(ConstantArray *CPA);
98 // isInlinableInst - Attempt to inline instructions into their uses to build
99 // trees as much as possible. To do this, we have to consistently decide
100 // what is acceptable to inline, so that variable declarations don't get
101 // printed and an extra copy of the expr is not emitted.
103 static bool isInlinableInst(const Instruction &I) {
104 // Must be an expression, must be used exactly once. If it is dead, we
105 // emit it inline where it would go.
106 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
107 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
108 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<VANextInst>(I))
109 // Don't inline a load across a store or other bad things!
112 // Only inline instruction it it's use is in the same BB as the inst.
113 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
116 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
117 // variables which are accessed with the & operator. This causes GCC to
118 // generate significantly better code than to emit alloca calls directly.
120 static const AllocaInst *isDirectAlloca(const Value *V) {
121 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
122 if (!AI) return false;
123 if (AI->isArrayAllocation())
124 return 0; // FIXME: we can also inline fixed size array allocas!
125 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
130 // Instruction visitation functions
131 friend class InstVisitor<CWriter>;
133 void visitReturnInst(ReturnInst &I);
134 void visitBranchInst(BranchInst &I);
135 void visitSwitchInst(SwitchInst &I);
136 void visitInvokeInst(InvokeInst &I);
137 void visitUnwindInst(UnwindInst &I);
139 void visitPHINode(PHINode &I);
140 void visitBinaryOperator(Instruction &I);
142 void visitCastInst (CastInst &I);
143 void visitCallInst (CallInst &I);
144 void visitCallSite (CallSite CS);
145 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
147 void visitMallocInst(MallocInst &I);
148 void visitAllocaInst(AllocaInst &I);
149 void visitFreeInst (FreeInst &I);
150 void visitLoadInst (LoadInst &I);
151 void visitStoreInst (StoreInst &I);
152 void visitGetElementPtrInst(GetElementPtrInst &I);
153 void visitVANextInst(VANextInst &I);
154 void visitVAArgInst (VAArgInst &I);
156 void visitInstruction(Instruction &I) {
157 std::cerr << "C Writer does not know about " << I;
161 void outputLValue(Instruction *I) {
162 Out << " " << Mang->getValueName(I) << " = ";
164 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
166 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
167 gep_type_iterator E);
171 // Pass the Type* and the variable name and this prints out the variable
174 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
175 const std::string &NameSoFar,
177 if (Ty->isPrimitiveType())
178 switch (Ty->getPrimitiveID()) {
179 case Type::VoidTyID: return Out << "void " << NameSoFar;
180 case Type::BoolTyID: return Out << "bool " << NameSoFar;
181 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
182 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
183 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
184 case Type::ShortTyID: return Out << "short " << NameSoFar;
185 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
186 case Type::IntTyID: return Out << "int " << NameSoFar;
187 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
188 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
189 case Type::FloatTyID: return Out << "float " << NameSoFar;
190 case Type::DoubleTyID: return Out << "double " << NameSoFar;
192 std::cerr << "Unknown primitive type: " << Ty << "\n";
196 // Check to see if the type is named.
197 if (!IgnoreName || isa<OpaqueType>(Ty)) {
198 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
199 if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
202 switch (Ty->getPrimitiveID()) {
203 case Type::FunctionTyID: {
204 const FunctionType *MTy = cast<FunctionType>(Ty);
205 std::stringstream FunctionInnards;
206 FunctionInnards << " (" << NameSoFar << ") (";
207 for (FunctionType::param_iterator I = MTy->param_begin(),
208 E = MTy->param_end(); I != E; ++I) {
209 if (I != MTy->param_begin())
210 FunctionInnards << ", ";
211 printType(FunctionInnards, *I, "");
213 if (MTy->isVarArg()) {
214 if (MTy->getNumParams())
215 FunctionInnards << ", ...";
216 } else if (!MTy->getNumParams()) {
217 FunctionInnards << "void";
219 FunctionInnards << ")";
220 std::string tstr = FunctionInnards.str();
221 printType(Out, MTy->getReturnType(), tstr);
224 case Type::StructTyID: {
225 const StructType *STy = cast<StructType>(Ty);
226 Out << NameSoFar + " {\n";
228 for (StructType::element_iterator I = STy->element_begin(),
229 E = STy->element_end(); I != E; ++I) {
231 printType(Out, *I, "field" + utostr(Idx++));
237 case Type::PointerTyID: {
238 const PointerType *PTy = cast<PointerType>(Ty);
239 std::string ptrName = "*" + NameSoFar;
241 if (isa<ArrayType>(PTy->getElementType()))
242 ptrName = "(" + ptrName + ")";
244 return printType(Out, PTy->getElementType(), ptrName);
247 case Type::ArrayTyID: {
248 const ArrayType *ATy = cast<ArrayType>(Ty);
249 unsigned NumElements = ATy->getNumElements();
250 return printType(Out, ATy->getElementType(),
251 NameSoFar + "[" + utostr(NumElements) + "]");
254 case Type::OpaqueTyID: {
255 static int Count = 0;
256 std::string TyName = "struct opaque_" + itostr(Count++);
257 assert(TypeNames.find(Ty) == TypeNames.end());
258 TypeNames[Ty] = TyName;
259 return Out << TyName << " " << NameSoFar;
262 assert(0 && "Unhandled case in getTypeProps!");
269 void CWriter::printConstantArray(ConstantArray *CPA) {
271 // As a special case, print the array as a string if it is an array of
272 // ubytes or an array of sbytes with positive values.
274 const Type *ETy = CPA->getType()->getElementType();
275 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
277 // Make sure the last character is a null char, as automatically added by C
278 if (isString && (CPA->getNumOperands() == 0 ||
279 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
284 // Keep track of whether the last number was a hexadecimal escape
285 bool LastWasHex = false;
287 // Do not include the last character, which we know is null
288 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
289 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
291 // Print it out literally if it is a printable character. The only thing
292 // to be careful about is when the last letter output was a hex escape
293 // code, in which case we have to be careful not to print out hex digits
294 // explicitly (the C compiler thinks it is a continuation of the previous
295 // character, sheesh...)
297 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
299 if (C == '"' || C == '\\')
306 case '\n': Out << "\\n"; break;
307 case '\t': Out << "\\t"; break;
308 case '\r': Out << "\\r"; break;
309 case '\v': Out << "\\v"; break;
310 case '\a': Out << "\\a"; break;
311 case '\"': Out << "\\\""; break;
312 case '\'': Out << "\\\'"; break;
315 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
316 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
325 if (CPA->getNumOperands()) {
327 printConstant(cast<Constant>(CPA->getOperand(0)));
328 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
330 printConstant(cast<Constant>(CPA->getOperand(i)));
337 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
338 // textually as a double (rather than as a reference to a stack-allocated
339 // variable). We decide this by converting CFP to a string and back into a
340 // double, and then checking whether the conversion results in a bit-equal
341 // double to the original value of CFP. This depends on us and the target C
342 // compiler agreeing on the conversion process (which is pretty likely since we
343 // only deal in IEEE FP).
345 bool isFPCSafeToPrint(const ConstantFP *CFP) {
348 sprintf(Buffer, "%a", CFP->getValue());
350 if (!strncmp(Buffer, "0x", 2) ||
351 !strncmp(Buffer, "-0x", 3) ||
352 !strncmp(Buffer, "+0x", 3))
353 return atof(Buffer) == CFP->getValue();
356 std::string StrVal = ftostr(CFP->getValue());
358 while (StrVal[0] == ' ')
359 StrVal.erase(StrVal.begin());
361 // Check to make sure that the stringized number is not some string like "Inf"
362 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
363 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
364 ((StrVal[0] == '-' || StrVal[0] == '+') &&
365 (StrVal[1] >= '0' && StrVal[1] <= '9')))
366 // Reparse stringized version!
367 return atof(StrVal.c_str()) == CFP->getValue();
372 // printConstant - The LLVM Constant to C Constant converter.
373 void CWriter::printConstant(Constant *CPV) {
374 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
375 switch (CE->getOpcode()) {
376 case Instruction::Cast:
378 printType(Out, CPV->getType());
380 printConstant(CE->getOperand(0));
384 case Instruction::GetElementPtr:
386 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
390 case Instruction::Add:
391 case Instruction::Sub:
392 case Instruction::Mul:
393 case Instruction::Div:
394 case Instruction::Rem:
395 case Instruction::SetEQ:
396 case Instruction::SetNE:
397 case Instruction::SetLT:
398 case Instruction::SetLE:
399 case Instruction::SetGT:
400 case Instruction::SetGE:
401 case Instruction::Shl:
402 case Instruction::Shr:
404 printConstant(CE->getOperand(0));
405 switch (CE->getOpcode()) {
406 case Instruction::Add: Out << " + "; break;
407 case Instruction::Sub: Out << " - "; break;
408 case Instruction::Mul: Out << " * "; break;
409 case Instruction::Div: Out << " / "; break;
410 case Instruction::Rem: Out << " % "; break;
411 case Instruction::SetEQ: Out << " == "; break;
412 case Instruction::SetNE: Out << " != "; break;
413 case Instruction::SetLT: Out << " < "; break;
414 case Instruction::SetLE: Out << " <= "; break;
415 case Instruction::SetGT: Out << " > "; break;
416 case Instruction::SetGE: Out << " >= "; break;
417 case Instruction::Shl: Out << " << "; break;
418 case Instruction::Shr: Out << " >> "; break;
419 default: assert(0 && "Illegal opcode here!");
421 printConstant(CE->getOperand(1));
426 std::cerr << "CWriter Error: Unhandled constant expression: "
432 switch (CPV->getType()->getPrimitiveID()) {
434 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
435 case Type::SByteTyID:
436 case Type::ShortTyID:
437 Out << cast<ConstantSInt>(CPV)->getValue(); break;
439 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
440 Out << "((int)0x80000000)"; // Handle MININT specially to avoid warning
442 Out << cast<ConstantSInt>(CPV)->getValue();
446 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
448 case Type::UByteTyID:
449 case Type::UShortTyID:
450 Out << cast<ConstantUInt>(CPV)->getValue(); break;
452 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
453 case Type::ULongTyID:
454 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
456 case Type::FloatTyID:
457 case Type::DoubleTyID: {
458 ConstantFP *FPC = cast<ConstantFP>(CPV);
459 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
460 if (I != FPConstantMap.end()) {
461 // Because of FP precision problems we must load from a stack allocated
462 // value that holds the value in hex.
463 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
464 << "*)&FPConstant" << I->second << ")";
467 // Print out the constant as a floating point number.
469 sprintf(Buffer, "%a", FPC->getValue());
470 Out << Buffer << " /*" << FPC->getValue() << "*/ ";
472 Out << ftostr(FPC->getValue());
478 case Type::ArrayTyID:
479 if (isa<ConstantAggregateZero>(CPV)) {
480 const ArrayType *AT = cast<ArrayType>(CPV->getType());
482 if (AT->getNumElements()) {
484 Constant *CZ = Constant::getNullValue(AT->getElementType());
486 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
493 printConstantArray(cast<ConstantArray>(CPV));
497 case Type::StructTyID:
498 if (isa<ConstantAggregateZero>(CPV)) {
499 const StructType *ST = cast<StructType>(CPV->getType());
501 if (ST->getNumElements()) {
503 printConstant(Constant::getNullValue(ST->getElementType(0)));
504 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
506 printConstant(Constant::getNullValue(ST->getElementType(i)));
512 if (CPV->getNumOperands()) {
514 printConstant(cast<Constant>(CPV->getOperand(0)));
515 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
517 printConstant(cast<Constant>(CPV->getOperand(i)));
524 case Type::PointerTyID:
525 if (isa<ConstantPointerNull>(CPV)) {
527 printType(Out, CPV->getType());
528 Out << ")/*NULL*/0)";
530 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
531 writeOperand(CPR->getValue());
536 std::cerr << "Unknown constant type: " << CPV << "\n";
541 void CWriter::writeOperandInternal(Value *Operand) {
542 if (Instruction *I = dyn_cast<Instruction>(Operand))
543 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
544 // Should we inline this instruction to build a tree?
551 if (Constant *CPV = dyn_cast<Constant>(Operand)) {
554 Out << Mang->getValueName(Operand);
558 void CWriter::writeOperand(Value *Operand) {
559 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
560 Out << "(&"; // Global variables are references as their addresses by llvm
562 writeOperandInternal(Operand);
564 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
568 // nameAllUsedStructureTypes - If there are structure types in the module that
569 // are used but do not have names assigned to them in the symbol table yet then
570 // we assign them names now.
572 bool CWriter::nameAllUsedStructureTypes(Module &M) {
573 // Get a set of types that are used by the program...
574 std::set<const Type *> UT = FUT->getTypes();
576 // Loop over the module symbol table, removing types from UT that are already
579 SymbolTable &MST = M.getSymbolTable();
580 if (MST.find(Type::TypeTy) != MST.end())
581 for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
582 E = MST.type_end(Type::TypeTy); I != E; ++I)
583 UT.erase(cast<Type>(I->second));
585 // UT now contains types that are not named. Loop over it, naming structure
588 bool Changed = false;
589 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
591 if (const StructType *ST = dyn_cast<StructType>(*I)) {
592 ((Value*)ST)->setName("unnamed", &MST);
598 // generateCompilerSpecificCode - This is where we add conditional compilation
599 // directives to cater to specific compilers as need be.
601 static void generateCompilerSpecificCode(std::ostream& Out) {
602 // Alloca is hard to get, and we don't want to include stdlib.h here...
603 Out << "/* get a declaration for alloca */\n"
605 << "extern void *__builtin_alloca(unsigned long);\n"
606 << "#define alloca(x) __builtin_alloca(x)\n"
608 << "#ifndef __FreeBSD__\n"
609 << "#include <alloca.h>\n"
613 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
614 // If we aren't being compiled with GCC, just drop these attributes.
615 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
616 << "#define __attribute__(X)\n"
620 // At some point, we should support "external weak" vs. "weak" linkages.
621 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
622 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
623 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
624 << "#elif defined(__GNUC__)\n"
625 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
627 << "#define __EXTERNAL_WEAK__\n"
631 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
632 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
633 << "#define __ATTRIBUTE_WEAK__\n"
634 << "#elif defined(__GNUC__)\n"
635 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
637 << "#define __ATTRIBUTE_WEAK__\n"
641 bool CWriter::doInitialization(Module &M) {
644 FUT = &getAnalysis<FindUsedTypes>();
646 // Ensure that all structure types have names...
647 bool Changed = nameAllUsedStructureTypes(M);
648 Mang = new Mangler(M);
650 // get declaration for alloca
651 Out << "/* Provide Declarations */\n";
652 Out << "#include <stdarg.h>\n"; // Varargs support
653 Out << "#include <setjmp.h>\n"; // Unwind support
654 generateCompilerSpecificCode(Out);
656 // Provide a definition for `bool' if not compiling with a C++ compiler.
658 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
660 << "\n\n/* Support for floating point constants */\n"
661 << "typedef unsigned long long ConstantDoubleTy;\n"
662 << "typedef unsigned int ConstantFloatTy;\n"
664 << "\n\n/* Global Declarations */\n";
666 // First output all the declarations for the program, because C requires
667 // Functions & globals to be declared before they are used.
670 // Loop over the symbol table, emitting all named constants...
671 printSymbolTable(M.getSymbolTable());
673 // Global variable declarations...
675 Out << "\n/* External Global Variable Declarations */\n";
676 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
677 if (I->hasExternalLinkage()) {
679 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
685 // Function declarations
687 Out << "\n/* Function Declarations */\n";
688 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
689 // Don't print declarations for intrinsic functions.
690 if (!I->getIntrinsicID()) {
691 printFunctionSignature(I, true);
692 if (I->hasWeakLinkage()) Out << " __ATTRIBUTE_WEAK__";
693 if (I->hasLinkOnceLinkage()) Out << " __ATTRIBUTE_WEAK__";
699 // Output the global variable declarations
701 Out << "\n\n/* Global Variable Declarations */\n";
702 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
703 if (!I->isExternal()) {
705 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
707 if (I->hasLinkOnceLinkage())
708 Out << " __attribute__((common))";
709 else if (I->hasWeakLinkage())
710 Out << " __ATTRIBUTE_WEAK__";
715 // Output the global variable definitions and contents...
717 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
718 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
719 if (!I->isExternal()) {
720 if (I->hasInternalLinkage())
722 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
723 if (I->hasLinkOnceLinkage())
724 Out << " __attribute__((common))";
725 else if (I->hasWeakLinkage())
726 Out << " __ATTRIBUTE_WEAK__";
728 // If the initializer is not null, emit the initializer. If it is null,
729 // we try to avoid emitting large amounts of zeros. The problem with
730 // this, however, occurs when the variable has weak linkage. In this
731 // case, the assembler will complain about the variable being both weak
732 // and common, so we disable this optimization.
733 if (!I->getInitializer()->isNullValue()) {
735 writeOperand(I->getInitializer());
736 } else if (I->hasWeakLinkage()) {
737 // We have to specify an initializer, but it doesn't have to be
738 // complete. If the value is an aggregate, print out { 0 }, and let
739 // the compiler figure out the rest of the zeros.
741 if (isa<StructType>(I->getInitializer()->getType()) ||
742 isa<ArrayType>(I->getInitializer()->getType())) {
745 // Just print it out normally.
746 writeOperand(I->getInitializer());
753 // Output all floating point constants that cannot be printed accurately...
754 printFloatingPointConstants(M);
757 Out << "\n\n/* Function Bodies */\n";
762 /// Output all floating point constants that cannot be printed accurately...
763 void CWriter::printFloatingPointConstants(Module &M) {
766 unsigned long long U;
774 // Scan the module for floating point constants. If any FP constant is used
775 // in the function, we want to redirect it here so that we do not depend on
776 // the precision of the printed form, unless the printed form preserves
779 unsigned FPCounter = 0;
780 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
781 for (constant_iterator I = constant_begin(F), E = constant_end(F);
783 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
784 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
785 !FPConstantMap.count(FPC)) {
786 double Val = FPC->getValue();
788 FPConstantMap[FPC] = FPCounter; // Number the FP constants
790 if (FPC->getType() == Type::DoubleTy) {
792 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
793 << " = 0x" << std::hex << DBLUnion.U << std::dec
794 << "ULL; /* " << Val << " */\n";
795 } else if (FPC->getType() == Type::FloatTy) {
797 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
798 << " = 0x" << std::hex << FLTUnion.U << std::dec
799 << "U; /* " << Val << " */\n";
801 assert(0 && "Unknown float type!");
808 /// printSymbolTable - Run through symbol table looking for type names. If a
809 /// type name is found, emit it's declaration...
811 void CWriter::printSymbolTable(const SymbolTable &ST) {
812 // If there are no type names, exit early.
813 if (ST.find(Type::TypeTy) == ST.end())
816 // We are only interested in the type plane of the symbol table...
817 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
818 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
820 // Print out forward declarations for structure types before anything else!
821 Out << "/* Structure forward decls */\n";
822 for (; I != End; ++I)
823 if (const Type *STy = dyn_cast<StructType>(I->second))
824 // Only print out used types!
825 if (FUT->getTypes().count(STy)) {
826 std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
827 Out << Name << ";\n";
828 TypeNames.insert(std::make_pair(STy, Name));
833 // Now we can print out typedefs...
834 Out << "/* Typedefs */\n";
835 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
836 // Only print out used types!
837 if (FUT->getTypes().count(cast<Type>(I->second))) {
838 const Type *Ty = cast<Type>(I->second);
839 std::string Name = "l_" + Mangler::makeNameProper(I->first);
841 printType(Out, Ty, Name);
847 // Keep track of which structures have been printed so far...
848 std::set<const StructType *> StructPrinted;
850 // Loop over all structures then push them into the stack so they are
851 // printed in the correct order.
853 Out << "/* Structure contents */\n";
854 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
855 if (const StructType *STy = dyn_cast<StructType>(I->second))
856 // Only print out used types!
857 if (FUT->getTypes().count(STy))
858 printContainedStructs(STy, StructPrinted);
861 // Push the struct onto the stack and recursively push all structs
862 // this one depends on.
863 void CWriter::printContainedStructs(const Type *Ty,
864 std::set<const StructType*> &StructPrinted){
865 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
866 //Check to see if we have already printed this struct
867 if (StructPrinted.count(STy) == 0) {
868 // Print all contained types first...
869 for (StructType::element_iterator I = STy->element_begin(),
870 E = STy->element_end(); I != E; ++I) {
871 const Type *Ty1 = I->get();
872 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
873 printContainedStructs(*I, StructPrinted);
876 //Print structure type out..
877 StructPrinted.insert(STy);
878 std::string Name = TypeNames[STy];
879 printType(Out, STy, Name, true);
883 // If it is an array, check contained types and continue
884 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
885 const Type *Ty1 = ATy->getElementType();
886 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
887 printContainedStructs(Ty1, StructPrinted);
892 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
893 if (F->hasInternalLinkage()) Out << "static ";
895 // Loop over the arguments, printing them...
896 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
898 std::stringstream FunctionInnards;
900 // Print out the name...
901 FunctionInnards << Mang->getValueName(F) << "(";
903 if (!F->isExternal()) {
906 if (F->abegin()->hasName() || !Prototype)
907 ArgName = Mang->getValueName(F->abegin());
908 printType(FunctionInnards, F->afront().getType(), ArgName);
909 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
911 FunctionInnards << ", ";
912 if (I->hasName() || !Prototype)
913 ArgName = Mang->getValueName(I);
916 printType(FunctionInnards, I->getType(), ArgName);
920 // Loop over the arguments, printing them...
921 for (FunctionType::param_iterator I = FT->param_begin(),
922 E = FT->param_end(); I != E; ++I) {
923 if (I != FT->param_begin()) FunctionInnards << ", ";
924 printType(FunctionInnards, *I);
928 // Finish printing arguments... if this is a vararg function, print the ...,
929 // unless there are no known types, in which case, we just emit ().
931 if (FT->isVarArg() && FT->getNumParams()) {
932 if (FT->getNumParams()) FunctionInnards << ", ";
933 FunctionInnards << "..."; // Output varargs portion of signature!
934 } else if (!FT->isVarArg() && FT->getNumParams() == 0) {
935 FunctionInnards << "void"; // ret() -> ret(void) in C.
937 FunctionInnards << ")";
938 // Print out the return type and the entire signature for that matter
939 printType(Out, F->getReturnType(), FunctionInnards.str());
942 void CWriter::printFunction(Function &F) {
943 printFunctionSignature(&F, false);
946 // print local variable information for the function
947 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
948 if (const AllocaInst *AI = isDirectAlloca(*I)) {
950 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
951 Out << "; /* Address exposed local */\n";
952 } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
954 printType(Out, (*I)->getType(), Mang->getValueName(*I));
957 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
959 printType(Out, (*I)->getType(),
960 Mang->getValueName(*I)+"__PHI_TEMPORARY");
967 // print the basic blocks
968 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
969 BasicBlock *Prev = BB->getPrev();
971 // Don't print the label for the basic block if there are no uses, or if the
972 // only terminator use is the predecessor basic block's terminator. We have
973 // to scan the use list because PHI nodes use basic blocks too but do not
974 // require a label to be generated.
976 bool NeedsLabel = false;
977 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
979 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
980 if (TI != Prev->getTerminator() ||
981 isa<SwitchInst>(Prev->getTerminator()) ||
982 isa<InvokeInst>(Prev->getTerminator())) {
987 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
989 // Output all of the instructions in the basic block...
990 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
991 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
992 if (II->getType() != Type::VoidTy)
1001 // Don't emit prefix or suffix for the terminator...
1002 visit(*BB->getTerminator());
1008 // Specific Instruction type classes... note that all of the casts are
1009 // necessary because we use the instruction classes as opaque types...
1011 void CWriter::visitReturnInst(ReturnInst &I) {
1012 // Don't output a void return if this is the last basic block in the function
1013 if (I.getNumOperands() == 0 &&
1014 &*--I.getParent()->getParent()->end() == I.getParent() &&
1015 !I.getParent()->size() == 1) {
1020 if (I.getNumOperands()) {
1022 writeOperand(I.getOperand(0));
1027 void CWriter::visitSwitchInst(SwitchInst &SI) {
1029 writeOperand(SI.getOperand(0));
1030 Out << ") {\n default:\n";
1031 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1033 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1035 writeOperand(SI.getOperand(i));
1037 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1038 printBranchToBlock(SI.getParent(), Succ, 2);
1039 if (Succ == SI.getParent()->getNext())
1045 void CWriter::visitInvokeInst(InvokeInst &II) {
1046 assert(0 && "Lowerinvoke pass didn't work!");
1050 void CWriter::visitUnwindInst(UnwindInst &I) {
1051 assert(0 && "Lowerinvoke pass didn't work!");
1054 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1055 // If PHI nodes need copies, we need the copy code...
1056 if (isa<PHINode>(To->front()) ||
1057 From->getNext() != To) // Not directly successor, need goto
1060 // Otherwise we don't need the code.
1064 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1066 for (BasicBlock::iterator I = Succ->begin();
1067 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1068 // now we have to do the printing
1069 Out << std::string(Indent, ' ');
1070 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1071 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
1072 Out << "; /* for PHI node */\n";
1075 if (CurBB->getNext() != Succ ||
1076 isa<InvokeInst>(CurBB->getTerminator()) ||
1077 isa<SwitchInst>(CurBB->getTerminator())) {
1078 Out << std::string(Indent, ' ') << " goto ";
1084 // Branch instruction printing - Avoid printing out a branch to a basic block
1085 // that immediately succeeds the current one.
1087 void CWriter::visitBranchInst(BranchInst &I) {
1088 if (I.isConditional()) {
1089 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1091 writeOperand(I.getCondition());
1094 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1096 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1097 Out << " } else {\n";
1098 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1101 // First goto not necessary, assume second one is...
1103 writeOperand(I.getCondition());
1106 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1111 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1116 // PHI nodes get copied into temporary values at the end of predecessor basic
1117 // blocks. We now need to copy these temporary values into the REAL value for
1119 void CWriter::visitPHINode(PHINode &I) {
1121 Out << "__PHI_TEMPORARY";
1125 void CWriter::visitBinaryOperator(Instruction &I) {
1126 // binary instructions, shift instructions, setCond instructions.
1127 assert(!isa<PointerType>(I.getType()));
1129 // We must cast the results of binary operations which might be promoted.
1130 bool needsCast = false;
1131 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1132 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1133 || (I.getType() == Type::FloatTy)) {
1136 printType(Out, I.getType());
1140 writeOperand(I.getOperand(0));
1142 switch (I.getOpcode()) {
1143 case Instruction::Add: Out << " + "; break;
1144 case Instruction::Sub: Out << " - "; break;
1145 case Instruction::Mul: Out << "*"; break;
1146 case Instruction::Div: Out << "/"; break;
1147 case Instruction::Rem: Out << "%"; break;
1148 case Instruction::And: Out << " & "; break;
1149 case Instruction::Or: Out << " | "; break;
1150 case Instruction::Xor: Out << " ^ "; break;
1151 case Instruction::SetEQ: Out << " == "; break;
1152 case Instruction::SetNE: Out << " != "; break;
1153 case Instruction::SetLE: Out << " <= "; break;
1154 case Instruction::SetGE: Out << " >= "; break;
1155 case Instruction::SetLT: Out << " < "; break;
1156 case Instruction::SetGT: Out << " > "; break;
1157 case Instruction::Shl : Out << " << "; break;
1158 case Instruction::Shr : Out << " >> "; break;
1159 default: std::cerr << "Invalid operator type!" << I; abort();
1162 writeOperand(I.getOperand(1));
1169 void CWriter::visitCastInst(CastInst &I) {
1170 if (I.getType() == Type::BoolTy) {
1172 writeOperand(I.getOperand(0));
1177 printType(Out, I.getType());
1179 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1180 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1181 // Avoid "cast to pointer from integer of different size" warnings
1185 writeOperand(I.getOperand(0));
1188 void CWriter::lowerIntrinsics(Module &M) {
1189 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1190 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1191 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1192 if (CallInst *CI = dyn_cast<CallInst>(I++))
1193 if (Function *F = CI->getCalledFunction())
1194 switch (F->getIntrinsicID()) {
1195 case Intrinsic::not_intrinsic:
1196 case Intrinsic::va_start:
1197 case Intrinsic::va_copy:
1198 case Intrinsic::va_end:
1199 case Intrinsic::returnaddress:
1200 case Intrinsic::frameaddress:
1201 case Intrinsic::setjmp:
1202 case Intrinsic::longjmp:
1203 // We directly implement these intrinsics
1206 // All other intrinsic calls we must lower.
1207 Instruction *Before = CI->getPrev();
1208 IL.LowerIntrinsicCall(CI);
1209 if (Before) { // Move iterator to instruction after call
1219 void CWriter::visitCallInst(CallInst &I) {
1220 // Handle intrinsic function calls first...
1221 if (Function *F = I.getCalledFunction())
1222 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1224 default: assert(0 && "Unknown LLVM intrinsic!");
1225 case Intrinsic::va_start:
1228 Out << "va_start(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1229 // Output the last argument to the enclosing function...
1230 if (I.getParent()->getParent()->aempty()) {
1231 std::cerr << "The C backend does not currently support zero "
1232 << "argument varargs functions, such as '"
1233 << I.getParent()->getParent()->getName() << "'!\n";
1236 writeOperand(&I.getParent()->getParent()->aback());
1239 case Intrinsic::va_end:
1240 Out << "va_end(*(va_list*)&";
1241 writeOperand(I.getOperand(1));
1244 case Intrinsic::va_copy:
1246 Out << "va_copy(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1247 Out << "*(va_list*)&";
1248 writeOperand(I.getOperand(1));
1251 case Intrinsic::returnaddress:
1252 Out << "__builtin_return_address(";
1253 writeOperand(I.getOperand(1));
1256 case Intrinsic::frameaddress:
1257 Out << "__builtin_frame_address(";
1258 writeOperand(I.getOperand(1));
1261 case Intrinsic::setjmp:
1262 Out << "setjmp(*(jmp_buf*)";
1263 writeOperand(I.getOperand(1));
1266 case Intrinsic::longjmp:
1267 Out << "longjmp(*(jmp_buf*)";
1268 writeOperand(I.getOperand(1));
1270 writeOperand(I.getOperand(2));
1278 void CWriter::visitCallSite(CallSite CS) {
1279 const PointerType *PTy = cast<PointerType>(CS.getCalledValue()->getType());
1280 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1281 const Type *RetTy = FTy->getReturnType();
1283 writeOperand(CS.getCalledValue());
1286 if (CS.arg_begin() != CS.arg_end()) {
1287 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1290 for (++AI; AI != AE; ++AI) {
1298 void CWriter::visitMallocInst(MallocInst &I) {
1299 assert(0 && "lowerallocations pass didn't work!");
1302 void CWriter::visitAllocaInst(AllocaInst &I) {
1304 printType(Out, I.getType());
1305 Out << ") alloca(sizeof(";
1306 printType(Out, I.getType()->getElementType());
1308 if (I.isArrayAllocation()) {
1310 writeOperand(I.getOperand(0));
1315 void CWriter::visitFreeInst(FreeInst &I) {
1316 assert(0 && "lowerallocations pass didn't work!");
1319 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1320 gep_type_iterator E) {
1321 bool HasImplicitAddress = false;
1322 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1323 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1324 HasImplicitAddress = true;
1325 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1326 HasImplicitAddress = true;
1327 Ptr = CPR->getValue(); // Get to the global...
1328 } else if (isDirectAlloca(Ptr)) {
1329 HasImplicitAddress = true;
1333 if (!HasImplicitAddress)
1334 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1336 writeOperandInternal(Ptr);
1340 const Constant *CI = dyn_cast<Constant>(I.getOperand());
1341 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1344 writeOperandInternal(Ptr);
1346 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1348 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1351 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1352 "Can only have implicit address with direct accessing");
1354 if (HasImplicitAddress) {
1356 } else if (CI && CI->isNullValue()) {
1357 gep_type_iterator TmpI = I; ++TmpI;
1359 // Print out the -> operator if possible...
1360 if (TmpI != E && isa<StructType>(*TmpI)) {
1361 Out << (HasImplicitAddress ? "." : "->");
1362 Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
1368 if (isa<StructType>(*I)) {
1369 Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
1372 writeOperand(I.getOperand());
1377 void CWriter::visitLoadInst(LoadInst &I) {
1379 writeOperand(I.getOperand(0));
1382 void CWriter::visitStoreInst(StoreInst &I) {
1384 writeOperand(I.getPointerOperand());
1386 writeOperand(I.getOperand(0));
1389 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1391 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
1395 void CWriter::visitVANextInst(VANextInst &I) {
1396 Out << Mang->getValueName(I.getOperand(0));
1397 Out << "; va_arg(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1398 printType(Out, I.getArgType());
1402 void CWriter::visitVAArgInst(VAArgInst &I) {
1404 Out << "{ va_list Tmp; va_copy(Tmp, *(va_list*)&";
1405 writeOperand(I.getOperand(0));
1406 Out << ");\n " << Mang->getValueName(&I) << " = va_arg(Tmp, ";
1407 printType(Out, I.getType());
1408 Out << ");\n va_end(Tmp); }";
1411 //===----------------------------------------------------------------------===//
1412 // External Interface declaration
1413 //===----------------------------------------------------------------------===//
1415 bool CTargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &o) {
1416 PM.add(createLowerAllocationsPass());
1417 PM.add(createLowerInvokePass());
1418 PM.add(new CWriter(o, getIntrinsicLowering()));
1422 TargetMachine *llvm::allocateCTargetMachine(const Module &M,
1423 IntrinsicLowering *IL) {
1424 return new CTargetMachine(M, IL);