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/ConstantsScanner.h"
27 #include "llvm/Analysis/FindUsedTypes.h"
28 #include "llvm/Analysis/LoopInfo.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Support/CallSite.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/GetElementPtrTypeIterator.h"
33 #include "llvm/Support/InstVisitor.h"
34 #include "llvm/Support/Mangler.h"
35 #include "Support/StringExtras.h"
36 #include "Config/config.h"
42 /// NameAllUsedStructs - This pass inserts names for any unnamed structure
43 /// types that are used by the program.
45 class CBackendNameAllUsedStructs : public Pass {
46 void getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.addRequired<FindUsedTypes>();
50 virtual const char *getPassName() const {
51 return "C backend type canonicalizer";
54 virtual bool run(Module &M);
57 /// CWriter - This class is the main chunk of code that converts an LLVM
58 /// module to a C translation unit.
59 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
61 IntrinsicLowering &IL;
64 const Module *TheModule;
65 std::map<const Type *, std::string> TypeNames;
67 std::map<const ConstantFP *, unsigned> FPConstantMap;
69 CWriter(std::ostream &o, IntrinsicLowering &il) : Out(o), IL(il) {}
71 virtual const char *getPassName() const { return "C backend"; }
73 void getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.addRequired<LoopInfo>();
78 virtual bool doInitialization(Module &M);
80 bool runOnFunction(Function &F) {
81 LI = &getAnalysis<LoopInfo>();
83 // Output all floating point constants that cannot be printed accurately.
84 printFloatingPointConstants(F);
88 FPConstantMap.clear();
92 virtual bool doFinalization(Module &M) {
99 std::ostream &printType(std::ostream &Out, const Type *Ty,
100 const std::string &VariableName = "",
101 bool IgnoreName = false);
103 void writeOperand(Value *Operand);
104 void writeOperandInternal(Value *Operand);
107 void lowerIntrinsics(Function &F);
109 bool nameAllUsedStructureTypes(Module &M);
110 void printModule(Module *M);
111 void printModuleTypes(const SymbolTable &ST);
112 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
113 void printFloatingPointConstants(Function &F);
114 void printFunctionSignature(const Function *F, bool Prototype);
116 void printFunction(Function &);
117 void printBasicBlock(BasicBlock *BB);
118 void printLoop(Loop *L);
120 void printConstant(Constant *CPV);
121 void printConstantArray(ConstantArray *CPA);
123 // isInlinableInst - Attempt to inline instructions into their uses to build
124 // trees as much as possible. To do this, we have to consistently decide
125 // what is acceptable to inline, so that variable declarations don't get
126 // printed and an extra copy of the expr is not emitted.
128 static bool isInlinableInst(const Instruction &I) {
129 // Must be an expression, must be used exactly once. If it is dead, we
130 // emit it inline where it would go.
131 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
132 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
133 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<VANextInst>(I))
134 // Don't inline a load across a store or other bad things!
137 // Only inline instruction it it's use is in the same BB as the inst.
138 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
141 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
142 // variables which are accessed with the & operator. This causes GCC to
143 // generate significantly better code than to emit alloca calls directly.
145 static const AllocaInst *isDirectAlloca(const Value *V) {
146 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
147 if (!AI) return false;
148 if (AI->isArrayAllocation())
149 return 0; // FIXME: we can also inline fixed size array allocas!
150 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
155 // Instruction visitation functions
156 friend class InstVisitor<CWriter>;
158 void visitReturnInst(ReturnInst &I);
159 void visitBranchInst(BranchInst &I);
160 void visitSwitchInst(SwitchInst &I);
161 void visitInvokeInst(InvokeInst &I) {
162 assert(0 && "Lowerinvoke pass didn't work!");
165 void visitUnwindInst(UnwindInst &I) {
166 assert(0 && "Lowerinvoke pass didn't work!");
169 void visitPHINode(PHINode &I);
170 void visitBinaryOperator(Instruction &I);
172 void visitCastInst (CastInst &I);
173 void visitSelectInst(SelectInst &I);
174 void visitCallInst (CallInst &I);
175 void visitCallSite (CallSite CS);
176 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
178 void visitMallocInst(MallocInst &I);
179 void visitAllocaInst(AllocaInst &I);
180 void visitFreeInst (FreeInst &I);
181 void visitLoadInst (LoadInst &I);
182 void visitStoreInst (StoreInst &I);
183 void visitGetElementPtrInst(GetElementPtrInst &I);
184 void visitVANextInst(VANextInst &I);
185 void visitVAArgInst (VAArgInst &I);
187 void visitInstruction(Instruction &I) {
188 std::cerr << "C Writer does not know about " << I;
192 void outputLValue(Instruction *I) {
193 Out << " " << Mang->getValueName(I) << " = ";
196 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
197 void printPHICopiesForSuccessors(BasicBlock *CurBlock,
199 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
201 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
202 gep_type_iterator E);
206 /// This method inserts names for any unnamed structure types that are used by
207 /// the program, and removes names from structure types that are not used by the
210 bool CBackendNameAllUsedStructs::run(Module &M) {
211 // Get a set of types that are used by the program...
212 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
214 // Loop over the module symbol table, removing types from UT that are
215 // already named, and removing names for structure types that are not used.
217 SymbolTable &MST = M.getSymbolTable();
218 if (MST.find(Type::TypeTy) != MST.end())
219 for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
220 E = MST.type_end(Type::TypeTy); I != E; ) {
221 SymbolTable::type_iterator It = I++;
222 if (StructType *STy = dyn_cast<StructType>(It->second)) {
223 // If this is not used, remove it from the symbol table.
224 std::set<const Type *>::iterator UTI = UT.find(STy);
226 MST.remove(It->first, It->second);
232 // UT now contains types that are not named. Loop over it, naming
235 bool Changed = false;
236 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
238 if (const StructType *ST = dyn_cast<StructType>(*I)) {
239 ((Value*)ST)->setName("unnamed", &MST);
246 // Pass the Type* and the variable name and this prints out the variable
249 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
250 const std::string &NameSoFar,
252 if (Ty->isPrimitiveType())
253 switch (Ty->getPrimitiveID()) {
254 case Type::VoidTyID: return Out << "void " << NameSoFar;
255 case Type::BoolTyID: return Out << "bool " << NameSoFar;
256 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
257 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
258 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
259 case Type::ShortTyID: return Out << "short " << NameSoFar;
260 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
261 case Type::IntTyID: return Out << "int " << NameSoFar;
262 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
263 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
264 case Type::FloatTyID: return Out << "float " << NameSoFar;
265 case Type::DoubleTyID: return Out << "double " << NameSoFar;
267 std::cerr << "Unknown primitive type: " << Ty << "\n";
271 // Check to see if the type is named.
272 if (!IgnoreName || isa<OpaqueType>(Ty)) {
273 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
274 if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
277 switch (Ty->getPrimitiveID()) {
278 case Type::FunctionTyID: {
279 const FunctionType *MTy = cast<FunctionType>(Ty);
280 std::stringstream FunctionInnards;
281 FunctionInnards << " (" << NameSoFar << ") (";
282 for (FunctionType::param_iterator I = MTy->param_begin(),
283 E = MTy->param_end(); I != E; ++I) {
284 if (I != MTy->param_begin())
285 FunctionInnards << ", ";
286 printType(FunctionInnards, *I, "");
288 if (MTy->isVarArg()) {
289 if (MTy->getNumParams())
290 FunctionInnards << ", ...";
291 } else if (!MTy->getNumParams()) {
292 FunctionInnards << "void";
294 FunctionInnards << ")";
295 std::string tstr = FunctionInnards.str();
296 printType(Out, MTy->getReturnType(), tstr);
299 case Type::StructTyID: {
300 const StructType *STy = cast<StructType>(Ty);
301 Out << NameSoFar + " {\n";
303 for (StructType::element_iterator I = STy->element_begin(),
304 E = STy->element_end(); I != E; ++I) {
306 printType(Out, *I, "field" + utostr(Idx++));
312 case Type::PointerTyID: {
313 const PointerType *PTy = cast<PointerType>(Ty);
314 std::string ptrName = "*" + NameSoFar;
316 if (isa<ArrayType>(PTy->getElementType()))
317 ptrName = "(" + ptrName + ")";
319 return printType(Out, PTy->getElementType(), ptrName);
322 case Type::ArrayTyID: {
323 const ArrayType *ATy = cast<ArrayType>(Ty);
324 unsigned NumElements = ATy->getNumElements();
325 return printType(Out, ATy->getElementType(),
326 NameSoFar + "[" + utostr(NumElements) + "]");
329 case Type::OpaqueTyID: {
330 static int Count = 0;
331 std::string TyName = "struct opaque_" + itostr(Count++);
332 assert(TypeNames.find(Ty) == TypeNames.end());
333 TypeNames[Ty] = TyName;
334 return Out << TyName << " " << NameSoFar;
337 assert(0 && "Unhandled case in getTypeProps!");
344 void CWriter::printConstantArray(ConstantArray *CPA) {
346 // As a special case, print the array as a string if it is an array of
347 // ubytes or an array of sbytes with positive values.
349 const Type *ETy = CPA->getType()->getElementType();
350 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
352 // Make sure the last character is a null char, as automatically added by C
353 if (isString && (CPA->getNumOperands() == 0 ||
354 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
359 // Keep track of whether the last number was a hexadecimal escape
360 bool LastWasHex = false;
362 // Do not include the last character, which we know is null
363 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
364 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
366 // Print it out literally if it is a printable character. The only thing
367 // to be careful about is when the last letter output was a hex escape
368 // code, in which case we have to be careful not to print out hex digits
369 // explicitly (the C compiler thinks it is a continuation of the previous
370 // character, sheesh...)
372 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
374 if (C == '"' || C == '\\')
381 case '\n': Out << "\\n"; break;
382 case '\t': Out << "\\t"; break;
383 case '\r': Out << "\\r"; break;
384 case '\v': Out << "\\v"; break;
385 case '\a': Out << "\\a"; break;
386 case '\"': Out << "\\\""; break;
387 case '\'': Out << "\\\'"; break;
390 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
391 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
400 if (CPA->getNumOperands()) {
402 printConstant(cast<Constant>(CPA->getOperand(0)));
403 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
405 printConstant(cast<Constant>(CPA->getOperand(i)));
412 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
413 // textually as a double (rather than as a reference to a stack-allocated
414 // variable). We decide this by converting CFP to a string and back into a
415 // double, and then checking whether the conversion results in a bit-equal
416 // double to the original value of CFP. This depends on us and the target C
417 // compiler agreeing on the conversion process (which is pretty likely since we
418 // only deal in IEEE FP).
420 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
423 sprintf(Buffer, "%a", CFP->getValue());
425 if (!strncmp(Buffer, "0x", 2) ||
426 !strncmp(Buffer, "-0x", 3) ||
427 !strncmp(Buffer, "+0x", 3))
428 return atof(Buffer) == CFP->getValue();
431 std::string StrVal = ftostr(CFP->getValue());
433 while (StrVal[0] == ' ')
434 StrVal.erase(StrVal.begin());
436 // Check to make sure that the stringized number is not some string like "Inf"
437 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
438 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
439 ((StrVal[0] == '-' || StrVal[0] == '+') &&
440 (StrVal[1] >= '0' && StrVal[1] <= '9')))
441 // Reparse stringized version!
442 return atof(StrVal.c_str()) == CFP->getValue();
447 // printConstant - The LLVM Constant to C Constant converter.
448 void CWriter::printConstant(Constant *CPV) {
449 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
450 switch (CE->getOpcode()) {
451 case Instruction::Cast:
453 printType(Out, CPV->getType());
455 printConstant(CE->getOperand(0));
459 case Instruction::GetElementPtr:
461 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
465 case Instruction::Select:
467 printConstant(CE->getOperand(0));
469 printConstant(CE->getOperand(1));
471 printConstant(CE->getOperand(2));
474 case Instruction::Add:
475 case Instruction::Sub:
476 case Instruction::Mul:
477 case Instruction::Div:
478 case Instruction::Rem:
479 case Instruction::SetEQ:
480 case Instruction::SetNE:
481 case Instruction::SetLT:
482 case Instruction::SetLE:
483 case Instruction::SetGT:
484 case Instruction::SetGE:
485 case Instruction::Shl:
486 case Instruction::Shr:
488 printConstant(CE->getOperand(0));
489 switch (CE->getOpcode()) {
490 case Instruction::Add: Out << " + "; break;
491 case Instruction::Sub: Out << " - "; break;
492 case Instruction::Mul: Out << " * "; break;
493 case Instruction::Div: Out << " / "; break;
494 case Instruction::Rem: Out << " % "; break;
495 case Instruction::SetEQ: Out << " == "; break;
496 case Instruction::SetNE: Out << " != "; break;
497 case Instruction::SetLT: Out << " < "; break;
498 case Instruction::SetLE: Out << " <= "; break;
499 case Instruction::SetGT: Out << " > "; break;
500 case Instruction::SetGE: Out << " >= "; break;
501 case Instruction::Shl: Out << " << "; break;
502 case Instruction::Shr: Out << " >> "; break;
503 default: assert(0 && "Illegal opcode here!");
505 printConstant(CE->getOperand(1));
510 std::cerr << "CWriter Error: Unhandled constant expression: "
516 switch (CPV->getType()->getPrimitiveID()) {
518 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
519 case Type::SByteTyID:
520 case Type::ShortTyID:
521 Out << cast<ConstantSInt>(CPV)->getValue(); break;
523 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
524 Out << "((int)0x80000000)"; // Handle MININT specially to avoid warning
526 Out << cast<ConstantSInt>(CPV)->getValue();
530 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
532 case Type::UByteTyID:
533 case Type::UShortTyID:
534 Out << cast<ConstantUInt>(CPV)->getValue(); break;
536 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
537 case Type::ULongTyID:
538 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
540 case Type::FloatTyID:
541 case Type::DoubleTyID: {
542 ConstantFP *FPC = cast<ConstantFP>(CPV);
543 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
544 if (I != FPConstantMap.end()) {
545 // Because of FP precision problems we must load from a stack allocated
546 // value that holds the value in hex.
547 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
548 << "*)&FPConstant" << I->second << ")";
551 // Print out the constant as a floating point number.
553 sprintf(Buffer, "%a", FPC->getValue());
554 Out << Buffer << " /*" << FPC->getValue() << "*/ ";
556 Out << ftostr(FPC->getValue());
562 case Type::ArrayTyID:
563 if (isa<ConstantAggregateZero>(CPV)) {
564 const ArrayType *AT = cast<ArrayType>(CPV->getType());
566 if (AT->getNumElements()) {
568 Constant *CZ = Constant::getNullValue(AT->getElementType());
570 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
577 printConstantArray(cast<ConstantArray>(CPV));
581 case Type::StructTyID:
582 if (isa<ConstantAggregateZero>(CPV)) {
583 const StructType *ST = cast<StructType>(CPV->getType());
585 if (ST->getNumElements()) {
587 printConstant(Constant::getNullValue(ST->getElementType(0)));
588 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
590 printConstant(Constant::getNullValue(ST->getElementType(i)));
596 if (CPV->getNumOperands()) {
598 printConstant(cast<Constant>(CPV->getOperand(0)));
599 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
601 printConstant(cast<Constant>(CPV->getOperand(i)));
608 case Type::PointerTyID:
609 if (isa<ConstantPointerNull>(CPV)) {
611 printType(Out, CPV->getType());
612 Out << ")/*NULL*/0)";
614 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
615 writeOperand(CPR->getValue());
620 std::cerr << "Unknown constant type: " << CPV << "\n";
625 void CWriter::writeOperandInternal(Value *Operand) {
626 if (Instruction *I = dyn_cast<Instruction>(Operand))
627 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
628 // Should we inline this instruction to build a tree?
635 if (Constant *CPV = dyn_cast<Constant>(Operand)) {
638 Out << Mang->getValueName(Operand);
642 void CWriter::writeOperand(Value *Operand) {
643 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
644 Out << "(&"; // Global variables are references as their addresses by llvm
646 writeOperandInternal(Operand);
648 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
652 // generateCompilerSpecificCode - This is where we add conditional compilation
653 // directives to cater to specific compilers as need be.
655 static void generateCompilerSpecificCode(std::ostream& Out) {
656 // Alloca is hard to get, and we don't want to include stdlib.h here...
657 Out << "/* get a declaration for alloca */\n"
659 << "extern void *__builtin_alloca(unsigned long);\n"
660 << "#define alloca(x) __builtin_alloca(x)\n"
662 << "#ifndef __FreeBSD__\n"
663 << "#include <alloca.h>\n"
667 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
668 // If we aren't being compiled with GCC, just drop these attributes.
669 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
670 << "#define __attribute__(X)\n"
674 // At some point, we should support "external weak" vs. "weak" linkages.
675 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
676 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
677 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
678 << "#elif defined(__GNUC__)\n"
679 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
681 << "#define __EXTERNAL_WEAK__\n"
685 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
686 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
687 << "#define __ATTRIBUTE_WEAK__\n"
688 << "#elif defined(__GNUC__)\n"
689 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
691 << "#define __ATTRIBUTE_WEAK__\n"
695 bool CWriter::doInitialization(Module &M) {
701 // Ensure that all structure types have names...
702 Mang = new Mangler(M);
704 // get declaration for alloca
705 Out << "/* Provide Declarations */\n";
706 Out << "#include <stdarg.h>\n"; // Varargs support
707 Out << "#include <setjmp.h>\n"; // Unwind support
708 generateCompilerSpecificCode(Out);
710 // Provide a definition for `bool' if not compiling with a C++ compiler.
712 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
714 << "\n\n/* Support for floating point constants */\n"
715 << "typedef unsigned long long ConstantDoubleTy;\n"
716 << "typedef unsigned int ConstantFloatTy;\n"
718 << "\n\n/* Global Declarations */\n";
720 // First output all the declarations for the program, because C requires
721 // Functions & globals to be declared before they are used.
724 // Loop over the symbol table, emitting all named constants...
725 printModuleTypes(M.getSymbolTable());
727 // Global variable declarations...
729 Out << "\n/* External Global Variable Declarations */\n";
730 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
731 if (I->hasExternalLinkage()) {
733 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
739 // Function declarations
741 Out << "\n/* Function Declarations */\n";
742 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
743 // Don't print declarations for intrinsic functions.
744 if (!I->getIntrinsicID() &&
745 I->getName() != "setjmp" && I->getName() != "longjmp") {
746 printFunctionSignature(I, true);
747 if (I->hasWeakLinkage()) Out << " __ATTRIBUTE_WEAK__";
748 if (I->hasLinkOnceLinkage()) Out << " __ATTRIBUTE_WEAK__";
754 // Output the global variable declarations
756 Out << "\n\n/* Global Variable Declarations */\n";
757 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
758 if (!I->isExternal()) {
760 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
762 if (I->hasLinkOnceLinkage())
763 Out << " __attribute__((common))";
764 else if (I->hasWeakLinkage())
765 Out << " __ATTRIBUTE_WEAK__";
770 // Output the global variable definitions and contents...
772 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
773 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
774 if (!I->isExternal()) {
775 if (I->hasInternalLinkage())
777 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
778 if (I->hasLinkOnceLinkage())
779 Out << " __attribute__((common))";
780 else if (I->hasWeakLinkage())
781 Out << " __ATTRIBUTE_WEAK__";
783 // If the initializer is not null, emit the initializer. If it is null,
784 // we try to avoid emitting large amounts of zeros. The problem with
785 // this, however, occurs when the variable has weak linkage. In this
786 // case, the assembler will complain about the variable being both weak
787 // and common, so we disable this optimization.
788 if (!I->getInitializer()->isNullValue()) {
790 writeOperand(I->getInitializer());
791 } else if (I->hasWeakLinkage()) {
792 // We have to specify an initializer, but it doesn't have to be
793 // complete. If the value is an aggregate, print out { 0 }, and let
794 // the compiler figure out the rest of the zeros.
796 if (isa<StructType>(I->getInitializer()->getType()) ||
797 isa<ArrayType>(I->getInitializer()->getType())) {
800 // Just print it out normally.
801 writeOperand(I->getInitializer());
809 Out << "\n\n/* Function Bodies */\n";
814 /// Output all floating point constants that cannot be printed accurately...
815 void CWriter::printFloatingPointConstants(Function &F) {
826 // Scan the module for floating point constants. If any FP constant is used
827 // in the function, we want to redirect it here so that we do not depend on
828 // the precision of the printed form, unless the printed form preserves
831 static unsigned FPCounter = 0;
832 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
834 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
835 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
836 !FPConstantMap.count(FPC)) {
837 double Val = FPC->getValue();
839 FPConstantMap[FPC] = FPCounter; // Number the FP constants
841 if (FPC->getType() == Type::DoubleTy) {
843 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
844 << " = 0x" << std::hex << DBLUnion.U << std::dec
845 << "ULL; /* " << Val << " */\n";
846 } else if (FPC->getType() == Type::FloatTy) {
848 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
849 << " = 0x" << std::hex << FLTUnion.U << std::dec
850 << "U; /* " << Val << " */\n";
852 assert(0 && "Unknown float type!");
859 /// printSymbolTable - Run through symbol table looking for type names. If a
860 /// type name is found, emit it's declaration...
862 void CWriter::printModuleTypes(const SymbolTable &ST) {
863 // If there are no type names, exit early.
864 if (ST.find(Type::TypeTy) == ST.end())
867 // We are only interested in the type plane of the symbol table...
868 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
869 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
871 // Print out forward declarations for structure types before anything else!
872 Out << "/* Structure forward decls */\n";
873 for (; I != End; ++I)
874 if (const Type *STy = dyn_cast<StructType>(I->second)) {
875 std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
876 Out << Name << ";\n";
877 TypeNames.insert(std::make_pair(STy, Name));
882 // Now we can print out typedefs...
883 Out << "/* Typedefs */\n";
884 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
885 const Type *Ty = cast<Type>(I->second);
886 std::string Name = "l_" + Mangler::makeNameProper(I->first);
888 printType(Out, Ty, Name);
894 // Keep track of which structures have been printed so far...
895 std::set<const StructType *> StructPrinted;
897 // Loop over all structures then push them into the stack so they are
898 // printed in the correct order.
900 Out << "/* Structure contents */\n";
901 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
902 if (const StructType *STy = dyn_cast<StructType>(I->second))
903 // Only print out used types!
904 printContainedStructs(STy, StructPrinted);
907 // Push the struct onto the stack and recursively push all structs
908 // this one depends on.
909 void CWriter::printContainedStructs(const Type *Ty,
910 std::set<const StructType*> &StructPrinted){
911 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
912 //Check to see if we have already printed this struct
913 if (StructPrinted.count(STy) == 0) {
914 // Print all contained types first...
915 for (StructType::element_iterator I = STy->element_begin(),
916 E = STy->element_end(); I != E; ++I) {
917 const Type *Ty1 = I->get();
918 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
919 printContainedStructs(*I, StructPrinted);
922 //Print structure type out..
923 StructPrinted.insert(STy);
924 std::string Name = TypeNames[STy];
925 printType(Out, STy, Name, true);
929 // If it is an array, check contained types and continue
930 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
931 const Type *Ty1 = ATy->getElementType();
932 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
933 printContainedStructs(Ty1, StructPrinted);
938 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
939 if (F->hasInternalLinkage()) Out << "static ";
941 // Loop over the arguments, printing them...
942 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
944 std::stringstream FunctionInnards;
946 // Print out the name...
947 FunctionInnards << Mang->getValueName(F) << "(";
949 if (!F->isExternal()) {
952 if (F->abegin()->hasName() || !Prototype)
953 ArgName = Mang->getValueName(F->abegin());
954 printType(FunctionInnards, F->afront().getType(), ArgName);
955 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
957 FunctionInnards << ", ";
958 if (I->hasName() || !Prototype)
959 ArgName = Mang->getValueName(I);
962 printType(FunctionInnards, I->getType(), ArgName);
966 // Loop over the arguments, printing them...
967 for (FunctionType::param_iterator I = FT->param_begin(),
968 E = FT->param_end(); I != E; ++I) {
969 if (I != FT->param_begin()) FunctionInnards << ", ";
970 printType(FunctionInnards, *I);
974 // Finish printing arguments... if this is a vararg function, print the ...,
975 // unless there are no known types, in which case, we just emit ().
977 if (FT->isVarArg() && FT->getNumParams()) {
978 if (FT->getNumParams()) FunctionInnards << ", ";
979 FunctionInnards << "..."; // Output varargs portion of signature!
980 } else if (!FT->isVarArg() && FT->getNumParams() == 0) {
981 FunctionInnards << "void"; // ret() -> ret(void) in C.
983 FunctionInnards << ")";
984 // Print out the return type and the entire signature for that matter
985 printType(Out, F->getReturnType(), FunctionInnards.str());
988 void CWriter::printFunction(Function &F) {
989 printFunctionSignature(&F, false);
992 // print local variable information for the function
993 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
994 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
996 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
997 Out << "; /* Address exposed local */\n";
998 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1000 printType(Out, I->getType(), Mang->getValueName(&*I));
1003 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1005 printType(Out, I->getType(),
1006 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
1013 // print the basic blocks
1014 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1015 if (Loop *L = LI->getLoopFor(BB)) {
1016 if (L->getHeader() == BB && L->getParentLoop() == 0)
1019 printBasicBlock(BB);
1026 void CWriter::printLoop(Loop *L) {
1027 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1028 << "' to make GCC happy */\n";
1029 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1030 BasicBlock *BB = L->getBlocks()[i];
1031 Loop *BBLoop = LI->getLoopFor(BB);
1033 printBasicBlock(BB);
1034 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1037 Out << " } while (1); /* end of syntactic loop '"
1038 << L->getHeader()->getName() << "' */\n";
1041 void CWriter::printBasicBlock(BasicBlock *BB) {
1043 // Don't print the label for the basic block if there are no uses, or if
1044 // the only terminator use is the predecessor basic block's terminator.
1045 // We have to scan the use list because PHI nodes use basic blocks too but
1046 // do not require a label to be generated.
1048 bool NeedsLabel = false;
1049 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1050 if (isGotoCodeNecessary(*PI, BB)) {
1055 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1057 // Output all of the instructions in the basic block...
1058 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1060 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1061 if (II->getType() != Type::VoidTy)
1070 // Don't emit prefix or suffix for the terminator...
1071 visit(*BB->getTerminator());
1075 // Specific Instruction type classes... note that all of the casts are
1076 // necessary because we use the instruction classes as opaque types...
1078 void CWriter::visitReturnInst(ReturnInst &I) {
1079 // Don't output a void return if this is the last basic block in the function
1080 if (I.getNumOperands() == 0 &&
1081 &*--I.getParent()->getParent()->end() == I.getParent() &&
1082 !I.getParent()->size() == 1) {
1087 if (I.getNumOperands()) {
1089 writeOperand(I.getOperand(0));
1094 void CWriter::visitSwitchInst(SwitchInst &SI) {
1095 printPHICopiesForSuccessors(SI.getParent(), 0);
1098 writeOperand(SI.getOperand(0));
1099 Out << ") {\n default:\n";
1100 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1102 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1104 writeOperand(SI.getOperand(i));
1106 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1107 printBranchToBlock(SI.getParent(), Succ, 2);
1108 if (Succ == SI.getParent()->getNext())
1114 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1115 /// FIXME: This should be reenabled, but loop reordering safe!!
1118 if (From->getNext() != To) // Not the direct successor, we need a goto
1121 //isa<SwitchInst>(From->getTerminator())
1124 if (LI->getLoopFor(From) != LI->getLoopFor(To))
1129 void CWriter::printPHICopiesForSuccessors(BasicBlock *CurBlock,
1131 for (succ_iterator SI = succ_begin(CurBlock), E = succ_end(CurBlock);
1133 for (BasicBlock::iterator I = SI->begin();
1134 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1135 // now we have to do the printing
1136 Out << std::string(Indent, ' ');
1137 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1138 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBlock)));
1139 Out << "; /* for PHI node */\n";
1144 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1146 if (isGotoCodeNecessary(CurBB, Succ)) {
1147 Out << std::string(Indent, ' ') << " goto ";
1153 // Branch instruction printing - Avoid printing out a branch to a basic block
1154 // that immediately succeeds the current one.
1156 void CWriter::visitBranchInst(BranchInst &I) {
1157 printPHICopiesForSuccessors(I.getParent(), 0);
1159 if (I.isConditional()) {
1160 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1162 writeOperand(I.getCondition());
1165 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1167 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1168 Out << " } else {\n";
1169 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1172 // First goto not necessary, assume second one is...
1174 writeOperand(I.getCondition());
1177 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1182 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1187 // PHI nodes get copied into temporary values at the end of predecessor basic
1188 // blocks. We now need to copy these temporary values into the REAL value for
1190 void CWriter::visitPHINode(PHINode &I) {
1192 Out << "__PHI_TEMPORARY";
1196 void CWriter::visitBinaryOperator(Instruction &I) {
1197 // binary instructions, shift instructions, setCond instructions.
1198 assert(!isa<PointerType>(I.getType()));
1200 // We must cast the results of binary operations which might be promoted.
1201 bool needsCast = false;
1202 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1203 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1204 || (I.getType() == Type::FloatTy)) {
1207 printType(Out, I.getType());
1211 writeOperand(I.getOperand(0));
1213 switch (I.getOpcode()) {
1214 case Instruction::Add: Out << " + "; break;
1215 case Instruction::Sub: Out << " - "; break;
1216 case Instruction::Mul: Out << "*"; break;
1217 case Instruction::Div: Out << "/"; break;
1218 case Instruction::Rem: Out << "%"; break;
1219 case Instruction::And: Out << " & "; break;
1220 case Instruction::Or: Out << " | "; break;
1221 case Instruction::Xor: Out << " ^ "; break;
1222 case Instruction::SetEQ: Out << " == "; break;
1223 case Instruction::SetNE: Out << " != "; break;
1224 case Instruction::SetLE: Out << " <= "; break;
1225 case Instruction::SetGE: Out << " >= "; break;
1226 case Instruction::SetLT: Out << " < "; break;
1227 case Instruction::SetGT: Out << " > "; break;
1228 case Instruction::Shl : Out << " << "; break;
1229 case Instruction::Shr : Out << " >> "; break;
1230 default: std::cerr << "Invalid operator type!" << I; abort();
1233 writeOperand(I.getOperand(1));
1240 void CWriter::visitCastInst(CastInst &I) {
1241 if (I.getType() == Type::BoolTy) {
1243 writeOperand(I.getOperand(0));
1248 printType(Out, I.getType());
1250 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1251 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1252 // Avoid "cast to pointer from integer of different size" warnings
1256 writeOperand(I.getOperand(0));
1259 void CWriter::visitSelectInst(SelectInst &I) {
1261 writeOperand(I.getCondition());
1263 writeOperand(I.getTrueValue());
1265 writeOperand(I.getFalseValue());
1270 void CWriter::lowerIntrinsics(Function &F) {
1271 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1272 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1273 if (CallInst *CI = dyn_cast<CallInst>(I++))
1274 if (Function *F = CI->getCalledFunction())
1275 switch (F->getIntrinsicID()) {
1276 case Intrinsic::not_intrinsic:
1277 case Intrinsic::vastart:
1278 case Intrinsic::vacopy:
1279 case Intrinsic::vaend:
1280 case Intrinsic::returnaddress:
1281 case Intrinsic::frameaddress:
1282 case Intrinsic::setjmp:
1283 case Intrinsic::longjmp:
1284 // We directly implement these intrinsics
1287 // All other intrinsic calls we must lower.
1288 Instruction *Before = CI->getPrev();
1289 IL.LowerIntrinsicCall(CI);
1290 if (Before) { // Move iterator to instruction after call
1300 void CWriter::visitCallInst(CallInst &I) {
1301 // Handle intrinsic function calls first...
1302 if (Function *F = I.getCalledFunction())
1303 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1305 default: assert(0 && "Unknown LLVM intrinsic!");
1306 case Intrinsic::vastart:
1309 Out << "va_start(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1310 // Output the last argument to the enclosing function...
1311 if (I.getParent()->getParent()->aempty()) {
1312 std::cerr << "The C backend does not currently support zero "
1313 << "argument varargs functions, such as '"
1314 << I.getParent()->getParent()->getName() << "'!\n";
1317 writeOperand(&I.getParent()->getParent()->aback());
1320 case Intrinsic::vaend:
1321 Out << "va_end(*(va_list*)&";
1322 writeOperand(I.getOperand(1));
1325 case Intrinsic::vacopy:
1327 Out << "va_copy(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1328 Out << "*(va_list*)&";
1329 writeOperand(I.getOperand(1));
1332 case Intrinsic::returnaddress:
1333 Out << "__builtin_return_address(";
1334 writeOperand(I.getOperand(1));
1337 case Intrinsic::frameaddress:
1338 Out << "__builtin_frame_address(";
1339 writeOperand(I.getOperand(1));
1342 case Intrinsic::setjmp:
1343 Out << "setjmp(*(jmp_buf*)";
1344 writeOperand(I.getOperand(1));
1347 case Intrinsic::longjmp:
1348 Out << "longjmp(*(jmp_buf*)";
1349 writeOperand(I.getOperand(1));
1351 writeOperand(I.getOperand(2));
1359 void CWriter::visitCallSite(CallSite CS) {
1360 const PointerType *PTy = cast<PointerType>(CS.getCalledValue()->getType());
1361 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1362 const Type *RetTy = FTy->getReturnType();
1364 writeOperand(CS.getCalledValue());
1367 if (CS.arg_begin() != CS.arg_end()) {
1368 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1371 for (++AI; AI != AE; ++AI) {
1379 void CWriter::visitMallocInst(MallocInst &I) {
1380 assert(0 && "lowerallocations pass didn't work!");
1383 void CWriter::visitAllocaInst(AllocaInst &I) {
1385 printType(Out, I.getType());
1386 Out << ") alloca(sizeof(";
1387 printType(Out, I.getType()->getElementType());
1389 if (I.isArrayAllocation()) {
1391 writeOperand(I.getOperand(0));
1396 void CWriter::visitFreeInst(FreeInst &I) {
1397 assert(0 && "lowerallocations pass didn't work!");
1400 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1401 gep_type_iterator E) {
1402 bool HasImplicitAddress = false;
1403 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1404 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1405 HasImplicitAddress = true;
1406 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1407 HasImplicitAddress = true;
1408 Ptr = CPR->getValue(); // Get to the global...
1409 } else if (isDirectAlloca(Ptr)) {
1410 HasImplicitAddress = true;
1414 if (!HasImplicitAddress)
1415 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1417 writeOperandInternal(Ptr);
1421 const Constant *CI = dyn_cast<Constant>(I.getOperand());
1422 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1425 writeOperandInternal(Ptr);
1427 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1429 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1432 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1433 "Can only have implicit address with direct accessing");
1435 if (HasImplicitAddress) {
1437 } else if (CI && CI->isNullValue()) {
1438 gep_type_iterator TmpI = I; ++TmpI;
1440 // Print out the -> operator if possible...
1441 if (TmpI != E && isa<StructType>(*TmpI)) {
1442 Out << (HasImplicitAddress ? "." : "->");
1443 Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
1449 if (isa<StructType>(*I)) {
1450 Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
1453 writeOperand(I.getOperand());
1458 void CWriter::visitLoadInst(LoadInst &I) {
1460 writeOperand(I.getOperand(0));
1463 void CWriter::visitStoreInst(StoreInst &I) {
1465 writeOperand(I.getPointerOperand());
1467 writeOperand(I.getOperand(0));
1470 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1472 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
1476 void CWriter::visitVANextInst(VANextInst &I) {
1477 Out << Mang->getValueName(I.getOperand(0));
1478 Out << "; va_arg(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1479 printType(Out, I.getArgType());
1483 void CWriter::visitVAArgInst(VAArgInst &I) {
1485 Out << "{ va_list Tmp; va_copy(Tmp, *(va_list*)&";
1486 writeOperand(I.getOperand(0));
1487 Out << ");\n " << Mang->getValueName(&I) << " = va_arg(Tmp, ";
1488 printType(Out, I.getType());
1489 Out << ");\n va_end(Tmp); }";
1492 //===----------------------------------------------------------------------===//
1493 // External Interface declaration
1494 //===----------------------------------------------------------------------===//
1496 bool CTargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &o) {
1497 PM.add(createLowerAllocationsPass());
1498 PM.add(createLowerInvokePass());
1499 PM.add(new CBackendNameAllUsedStructs());
1500 PM.add(new CWriter(o, getIntrinsicLowering()));
1504 TargetMachine *llvm::allocateCTargetMachine(const Module &M,
1505 IntrinsicLowering *IL) {
1506 return new CTargetMachine(M, IL);