1 //===-- CBackend.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/CallingConv.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/TypeSymbolTable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/Analysis/ConstantsScanner.h"
28 #include "llvm/Analysis/FindUsedTypes.h"
29 #include "llvm/Analysis/LoopInfo.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Target/TargetMachineRegistry.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetData.h"
35 #include "llvm/Support/CallSite.h"
36 #include "llvm/Support/CFG.h"
37 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 #include "llvm/Support/InstVisitor.h"
39 #include "llvm/Support/Mangler.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/ADT/StringExtras.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Config/config.h"
50 // Register the target.
51 RegisterTarget<CTargetMachine> X("c", " C backend");
53 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
54 /// any unnamed structure types that are used by the program, and merges
55 /// external functions with the same name.
57 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
58 void getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.addRequired<FindUsedTypes>();
62 virtual const char *getPassName() const {
63 return "C backend type canonicalizer";
66 virtual bool runOnModule(Module &M);
69 /// CWriter - This class is the main chunk of code that converts an LLVM
70 /// module to a C translation unit.
71 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
73 IntrinsicLowering *IL;
76 const Module *TheModule;
77 const TargetAsmInfo* TAsm;
79 std::map<const Type *, std::string> TypeNames;
81 std::map<const ConstantFP *, unsigned> FPConstantMap;
83 CWriter(std::ostream &o) : Out(o), IL(0), Mang(0), LI(0), TheModule(0),
86 virtual const char *getPassName() const { return "C backend"; }
88 void getAnalysisUsage(AnalysisUsage &AU) const {
89 AU.addRequired<LoopInfo>();
93 virtual bool doInitialization(Module &M);
95 bool runOnFunction(Function &F) {
96 LI = &getAnalysis<LoopInfo>();
98 // Get rid of intrinsics we can't handle.
101 // Output all floating point constants that cannot be printed accurately.
102 printFloatingPointConstants(F);
105 FPConstantMap.clear();
109 virtual bool doFinalization(Module &M) {
116 std::ostream &printType(std::ostream &Out, const Type *Ty,
117 bool isSigned = false,
118 const std::string &VariableName = "",
119 bool IgnoreName = false);
120 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
122 const std::string &NameSoFar = "");
124 void printStructReturnPointerFunctionType(std::ostream &Out,
125 const PointerType *Ty);
127 void writeOperand(Value *Operand);
128 void writeOperandRaw(Value *Operand);
129 void writeOperandInternal(Value *Operand);
130 void writeOperandWithCast(Value* Operand, unsigned Opcode);
131 void writeOperandWithCast(Value* Operand, ICmpInst::Predicate predicate);
132 bool writeInstructionCast(const Instruction &I);
135 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
137 void lowerIntrinsics(Function &F);
139 void printModule(Module *M);
140 void printModuleTypes(const TypeSymbolTable &ST);
141 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
142 void printFloatingPointConstants(Function &F);
143 void printFunctionSignature(const Function *F, bool Prototype);
145 void printFunction(Function &);
146 void printBasicBlock(BasicBlock *BB);
147 void printLoop(Loop *L);
149 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
150 void printConstant(Constant *CPV);
151 void printConstantWithCast(Constant *CPV, unsigned Opcode);
152 bool printConstExprCast(const ConstantExpr *CE);
153 void printConstantArray(ConstantArray *CPA);
154 void printConstantVector(ConstantVector *CP);
156 // isInlinableInst - Attempt to inline instructions into their uses to build
157 // trees as much as possible. To do this, we have to consistently decide
158 // what is acceptable to inline, so that variable declarations don't get
159 // printed and an extra copy of the expr is not emitted.
161 static bool isInlinableInst(const Instruction &I) {
162 // Always inline cmp instructions, even if they are shared by multiple
163 // expressions. GCC generates horrible code if we don't.
167 // Must be an expression, must be used exactly once. If it is dead, we
168 // emit it inline where it would go.
169 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
170 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
171 isa<LoadInst>(I) || isa<VAArgInst>(I))
172 // Don't inline a load across a store or other bad things!
175 // Must not be used in inline asm
176 if (I.hasOneUse() && isInlineAsm(*I.use_back())) return false;
178 // Only inline instruction it if it's use is in the same BB as the inst.
179 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
182 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
183 // variables which are accessed with the & operator. This causes GCC to
184 // generate significantly better code than to emit alloca calls directly.
186 static const AllocaInst *isDirectAlloca(const Value *V) {
187 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
188 if (!AI) return false;
189 if (AI->isArrayAllocation())
190 return 0; // FIXME: we can also inline fixed size array allocas!
191 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
196 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
197 static bool isInlineAsm(const Instruction& I) {
198 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
203 // Instruction visitation functions
204 friend class InstVisitor<CWriter>;
206 void visitReturnInst(ReturnInst &I);
207 void visitBranchInst(BranchInst &I);
208 void visitSwitchInst(SwitchInst &I);
209 void visitInvokeInst(InvokeInst &I) {
210 assert(0 && "Lowerinvoke pass didn't work!");
213 void visitUnwindInst(UnwindInst &I) {
214 assert(0 && "Lowerinvoke pass didn't work!");
216 void visitUnreachableInst(UnreachableInst &I);
218 void visitPHINode(PHINode &I);
219 void visitBinaryOperator(Instruction &I);
220 void visitICmpInst(ICmpInst &I);
221 void visitFCmpInst(FCmpInst &I);
223 void visitCastInst (CastInst &I);
224 void visitSelectInst(SelectInst &I);
225 void visitCallInst (CallInst &I);
226 void visitInlineAsm(CallInst &I);
228 void visitMallocInst(MallocInst &I);
229 void visitAllocaInst(AllocaInst &I);
230 void visitFreeInst (FreeInst &I);
231 void visitLoadInst (LoadInst &I);
232 void visitStoreInst (StoreInst &I);
233 void visitGetElementPtrInst(GetElementPtrInst &I);
234 void visitVAArgInst (VAArgInst &I);
236 void visitInstruction(Instruction &I) {
237 cerr << "C Writer does not know about " << I;
241 void outputLValue(Instruction *I) {
242 Out << " " << Mang->getValueName(I) << " = ";
245 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
246 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
247 BasicBlock *Successor, unsigned Indent);
248 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
250 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
251 gep_type_iterator E);
255 /// This method inserts names for any unnamed structure types that are used by
256 /// the program, and removes names from structure types that are not used by the
259 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
260 // Get a set of types that are used by the program...
261 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
263 // Loop over the module symbol table, removing types from UT that are
264 // already named, and removing names for types that are not used.
266 TypeSymbolTable &TST = M.getTypeSymbolTable();
267 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
269 TypeSymbolTable::iterator I = TI++;
271 // If this isn't a struct type, remove it from our set of types to name.
272 // This simplifies emission later.
273 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second)) {
276 // If this is not used, remove it from the symbol table.
277 std::set<const Type *>::iterator UTI = UT.find(I->second);
281 UT.erase(UTI); // Only keep one name for this type.
285 // UT now contains types that are not named. Loop over it, naming
288 bool Changed = false;
289 unsigned RenameCounter = 0;
290 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
292 if (const StructType *ST = dyn_cast<StructType>(*I)) {
293 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
299 // Loop over all external functions and globals. If we have two with
300 // identical names, merge them.
301 // FIXME: This code should disappear when we don't allow values with the same
302 // names when they have different types!
303 std::map<std::string, GlobalValue*> ExtSymbols;
304 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
306 if (GV->isDeclaration() && GV->hasName()) {
307 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
308 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
310 // Found a conflict, replace this global with the previous one.
311 GlobalValue *OldGV = X.first->second;
312 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
313 GV->eraseFromParent();
318 // Do the same for globals.
319 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
321 GlobalVariable *GV = I++;
322 if (GV->isDeclaration() && GV->hasName()) {
323 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
324 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
326 // Found a conflict, replace this global with the previous one.
327 GlobalValue *OldGV = X.first->second;
328 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
329 GV->eraseFromParent();
338 /// printStructReturnPointerFunctionType - This is like printType for a struct
339 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
340 /// print it as "Struct (*)(...)", for struct return functions.
341 void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
342 const PointerType *TheTy) {
343 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
344 std::stringstream FunctionInnards;
345 FunctionInnards << " (*) (";
346 bool PrintedType = false;
348 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
349 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
351 for (++I; I != E; ++I) {
353 FunctionInnards << ", ";
354 printType(FunctionInnards, *I,
355 /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute), "");
358 if (FTy->isVarArg()) {
360 FunctionInnards << ", ...";
361 } else if (!PrintedType) {
362 FunctionInnards << "void";
364 FunctionInnards << ')';
365 std::string tstr = FunctionInnards.str();
366 printType(Out, RetTy,
367 /*isSigned=*/FTy->paramHasAttr(0, FunctionType::SExtAttribute), tstr);
371 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
372 const std::string &NameSoFar) {
373 assert((Ty->isPrimitiveType() || Ty->isInteger()) &&
374 "Invalid type for printSimpleType");
375 switch (Ty->getTypeID()) {
376 case Type::VoidTyID: return Out << "void " << NameSoFar;
377 case Type::IntegerTyID: {
378 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
380 return Out << "bool " << NameSoFar;
381 else if (NumBits <= 8)
382 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
383 else if (NumBits <= 16)
384 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
385 else if (NumBits <= 32)
386 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
388 assert(NumBits <= 64 && "Bit widths > 64 not implemented yet");
389 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
392 case Type::FloatTyID: return Out << "float " << NameSoFar;
393 case Type::DoubleTyID: return Out << "double " << NameSoFar;
395 cerr << "Unknown primitive type: " << *Ty << "\n";
400 // Pass the Type* and the variable name and this prints out the variable
403 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
404 bool isSigned, const std::string &NameSoFar,
406 if (Ty->isPrimitiveType() || Ty->isInteger()) {
407 printSimpleType(Out, Ty, isSigned, NameSoFar);
411 // Check to see if the type is named.
412 if (!IgnoreName || isa<OpaqueType>(Ty)) {
413 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
414 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
417 switch (Ty->getTypeID()) {
418 case Type::FunctionTyID: {
419 const FunctionType *FTy = cast<FunctionType>(Ty);
420 std::stringstream FunctionInnards;
421 FunctionInnards << " (" << NameSoFar << ") (";
423 for (FunctionType::param_iterator I = FTy->param_begin(),
424 E = FTy->param_end(); I != E; ++I) {
425 if (I != FTy->param_begin())
426 FunctionInnards << ", ";
427 printType(FunctionInnards, *I,
428 /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute), "");
431 if (FTy->isVarArg()) {
432 if (FTy->getNumParams())
433 FunctionInnards << ", ...";
434 } else if (!FTy->getNumParams()) {
435 FunctionInnards << "void";
437 FunctionInnards << ')';
438 std::string tstr = FunctionInnards.str();
439 printType(Out, FTy->getReturnType(),
440 /*isSigned=*/FTy->paramHasAttr(0, FunctionType::SExtAttribute), tstr);
443 case Type::StructTyID: {
444 const StructType *STy = cast<StructType>(Ty);
445 Out << NameSoFar + " {\n";
447 for (StructType::element_iterator I = STy->element_begin(),
448 E = STy->element_end(); I != E; ++I) {
450 printType(Out, *I, false, "field" + utostr(Idx++));
456 case Type::PointerTyID: {
457 const PointerType *PTy = cast<PointerType>(Ty);
458 std::string ptrName = "*" + NameSoFar;
460 if (isa<ArrayType>(PTy->getElementType()) ||
461 isa<VectorType>(PTy->getElementType()))
462 ptrName = "(" + ptrName + ")";
464 return printType(Out, PTy->getElementType(), false, ptrName);
467 case Type::ArrayTyID: {
468 const ArrayType *ATy = cast<ArrayType>(Ty);
469 unsigned NumElements = ATy->getNumElements();
470 if (NumElements == 0) NumElements = 1;
471 return printType(Out, ATy->getElementType(), false,
472 NameSoFar + "[" + utostr(NumElements) + "]");
475 case Type::VectorTyID: {
476 const VectorType *PTy = cast<VectorType>(Ty);
477 unsigned NumElements = PTy->getNumElements();
478 if (NumElements == 0) NumElements = 1;
479 return printType(Out, PTy->getElementType(), false,
480 NameSoFar + "[" + utostr(NumElements) + "]");
483 case Type::OpaqueTyID: {
484 static int Count = 0;
485 std::string TyName = "struct opaque_" + itostr(Count++);
486 assert(TypeNames.find(Ty) == TypeNames.end());
487 TypeNames[Ty] = TyName;
488 return Out << TyName << ' ' << NameSoFar;
491 assert(0 && "Unhandled case in getTypeProps!");
498 void CWriter::printConstantArray(ConstantArray *CPA) {
500 // As a special case, print the array as a string if it is an array of
501 // ubytes or an array of sbytes with positive values.
503 const Type *ETy = CPA->getType()->getElementType();
504 bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
506 // Make sure the last character is a null char, as automatically added by C
507 if (isString && (CPA->getNumOperands() == 0 ||
508 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
513 // Keep track of whether the last number was a hexadecimal escape
514 bool LastWasHex = false;
516 // Do not include the last character, which we know is null
517 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
518 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
520 // Print it out literally if it is a printable character. The only thing
521 // to be careful about is when the last letter output was a hex escape
522 // code, in which case we have to be careful not to print out hex digits
523 // explicitly (the C compiler thinks it is a continuation of the previous
524 // character, sheesh...)
526 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
528 if (C == '"' || C == '\\')
535 case '\n': Out << "\\n"; break;
536 case '\t': Out << "\\t"; break;
537 case '\r': Out << "\\r"; break;
538 case '\v': Out << "\\v"; break;
539 case '\a': Out << "\\a"; break;
540 case '\"': Out << "\\\""; break;
541 case '\'': Out << "\\\'"; break;
544 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
545 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
554 if (CPA->getNumOperands()) {
556 printConstant(cast<Constant>(CPA->getOperand(0)));
557 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
559 printConstant(cast<Constant>(CPA->getOperand(i)));
566 void CWriter::printConstantVector(ConstantVector *CP) {
568 if (CP->getNumOperands()) {
570 printConstant(cast<Constant>(CP->getOperand(0)));
571 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
573 printConstant(cast<Constant>(CP->getOperand(i)));
579 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
580 // textually as a double (rather than as a reference to a stack-allocated
581 // variable). We decide this by converting CFP to a string and back into a
582 // double, and then checking whether the conversion results in a bit-equal
583 // double to the original value of CFP. This depends on us and the target C
584 // compiler agreeing on the conversion process (which is pretty likely since we
585 // only deal in IEEE FP).
587 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
588 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
590 sprintf(Buffer, "%a", CFP->getValue());
592 if (!strncmp(Buffer, "0x", 2) ||
593 !strncmp(Buffer, "-0x", 3) ||
594 !strncmp(Buffer, "+0x", 3))
595 return atof(Buffer) == CFP->getValue();
598 std::string StrVal = ftostr(CFP->getValue());
600 while (StrVal[0] == ' ')
601 StrVal.erase(StrVal.begin());
603 // Check to make sure that the stringized number is not some string like "Inf"
604 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
605 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
606 ((StrVal[0] == '-' || StrVal[0] == '+') &&
607 (StrVal[1] >= '0' && StrVal[1] <= '9')))
608 // Reparse stringized version!
609 return atof(StrVal.c_str()) == CFP->getValue();
614 /// Print out the casting for a cast operation. This does the double casting
615 /// necessary for conversion to the destination type, if necessary.
616 /// @brief Print a cast
617 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
618 // Print the destination type cast
620 case Instruction::UIToFP:
621 case Instruction::SIToFP:
622 case Instruction::IntToPtr:
623 case Instruction::Trunc:
624 case Instruction::BitCast:
625 case Instruction::FPExt:
626 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
628 printType(Out, DstTy);
631 case Instruction::ZExt:
632 case Instruction::PtrToInt:
633 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
635 printSimpleType(Out, DstTy, false);
638 case Instruction::SExt:
639 case Instruction::FPToSI: // For these, make sure we get a signed dest
641 printSimpleType(Out, DstTy, true);
645 assert(0 && "Invalid cast opcode");
648 // Print the source type cast
650 case Instruction::UIToFP:
651 case Instruction::ZExt:
653 printSimpleType(Out, SrcTy, false);
656 case Instruction::SIToFP:
657 case Instruction::SExt:
659 printSimpleType(Out, SrcTy, true);
662 case Instruction::IntToPtr:
663 case Instruction::PtrToInt:
664 // Avoid "cast to pointer from integer of different size" warnings
665 Out << "(unsigned long)";
667 case Instruction::Trunc:
668 case Instruction::BitCast:
669 case Instruction::FPExt:
670 case Instruction::FPTrunc:
671 case Instruction::FPToSI:
672 case Instruction::FPToUI:
673 break; // These don't need a source cast.
675 assert(0 && "Invalid cast opcode");
680 // printConstant - The LLVM Constant to C Constant converter.
681 void CWriter::printConstant(Constant *CPV) {
682 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
683 switch (CE->getOpcode()) {
684 case Instruction::Trunc:
685 case Instruction::ZExt:
686 case Instruction::SExt:
687 case Instruction::FPTrunc:
688 case Instruction::FPExt:
689 case Instruction::UIToFP:
690 case Instruction::SIToFP:
691 case Instruction::FPToUI:
692 case Instruction::FPToSI:
693 case Instruction::PtrToInt:
694 case Instruction::IntToPtr:
695 case Instruction::BitCast:
697 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
698 if (CE->getOpcode() == Instruction::SExt &&
699 CE->getOperand(0)->getType() == Type::Int1Ty) {
700 // Make sure we really sext from bool here by subtracting from 0
703 printConstant(CE->getOperand(0));
704 if (CE->getType() == Type::Int1Ty &&
705 (CE->getOpcode() == Instruction::Trunc ||
706 CE->getOpcode() == Instruction::FPToUI ||
707 CE->getOpcode() == Instruction::FPToSI ||
708 CE->getOpcode() == Instruction::PtrToInt)) {
709 // Make sure we really truncate to bool here by anding with 1
715 case Instruction::GetElementPtr:
717 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
721 case Instruction::Select:
723 printConstant(CE->getOperand(0));
725 printConstant(CE->getOperand(1));
727 printConstant(CE->getOperand(2));
730 case Instruction::Add:
731 case Instruction::Sub:
732 case Instruction::Mul:
733 case Instruction::SDiv:
734 case Instruction::UDiv:
735 case Instruction::FDiv:
736 case Instruction::URem:
737 case Instruction::SRem:
738 case Instruction::FRem:
739 case Instruction::And:
740 case Instruction::Or:
741 case Instruction::Xor:
742 case Instruction::ICmp:
743 case Instruction::Shl:
744 case Instruction::LShr:
745 case Instruction::AShr:
748 bool NeedsClosingParens = printConstExprCast(CE);
749 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
750 switch (CE->getOpcode()) {
751 case Instruction::Add: Out << " + "; break;
752 case Instruction::Sub: Out << " - "; break;
753 case Instruction::Mul: Out << " * "; break;
754 case Instruction::URem:
755 case Instruction::SRem:
756 case Instruction::FRem: Out << " % "; break;
757 case Instruction::UDiv:
758 case Instruction::SDiv:
759 case Instruction::FDiv: Out << " / "; break;
760 case Instruction::And: Out << " & "; break;
761 case Instruction::Or: Out << " | "; break;
762 case Instruction::Xor: Out << " ^ "; break;
763 case Instruction::Shl: Out << " << "; break;
764 case Instruction::LShr:
765 case Instruction::AShr: Out << " >> "; break;
766 case Instruction::ICmp:
767 switch (CE->getPredicate()) {
768 case ICmpInst::ICMP_EQ: Out << " == "; break;
769 case ICmpInst::ICMP_NE: Out << " != "; break;
770 case ICmpInst::ICMP_SLT:
771 case ICmpInst::ICMP_ULT: Out << " < "; break;
772 case ICmpInst::ICMP_SLE:
773 case ICmpInst::ICMP_ULE: Out << " <= "; break;
774 case ICmpInst::ICMP_SGT:
775 case ICmpInst::ICMP_UGT: Out << " > "; break;
776 case ICmpInst::ICMP_SGE:
777 case ICmpInst::ICMP_UGE: Out << " >= "; break;
778 default: assert(0 && "Illegal ICmp predicate");
781 default: assert(0 && "Illegal opcode here!");
783 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
784 if (NeedsClosingParens)
789 case Instruction::FCmp: {
791 bool NeedsClosingParens = printConstExprCast(CE);
792 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
794 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
798 switch (CE->getPredicate()) {
799 default: assert(0 && "Illegal FCmp predicate");
800 case FCmpInst::FCMP_ORD: op = "ord"; break;
801 case FCmpInst::FCMP_UNO: op = "uno"; break;
802 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
803 case FCmpInst::FCMP_UNE: op = "une"; break;
804 case FCmpInst::FCMP_ULT: op = "ult"; break;
805 case FCmpInst::FCMP_ULE: op = "ule"; break;
806 case FCmpInst::FCMP_UGT: op = "ugt"; break;
807 case FCmpInst::FCMP_UGE: op = "uge"; break;
808 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
809 case FCmpInst::FCMP_ONE: op = "one"; break;
810 case FCmpInst::FCMP_OLT: op = "olt"; break;
811 case FCmpInst::FCMP_OLE: op = "ole"; break;
812 case FCmpInst::FCMP_OGT: op = "ogt"; break;
813 case FCmpInst::FCMP_OGE: op = "oge"; break;
815 Out << "llvm_fcmp_" << op << "(";
816 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
818 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
821 if (NeedsClosingParens)
826 cerr << "CWriter Error: Unhandled constant expression: "
830 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
832 printType(Out, CPV->getType()); // sign doesn't matter
833 Out << ")/*UNDEF*/0)";
837 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
838 const Type* Ty = CI->getType();
839 if (Ty == Type::Int1Ty)
840 Out << (CI->getZExtValue() ? '1' : '0') ;
843 printSimpleType(Out, Ty, false) << ')';
844 if (CI->isMinValue(true))
845 Out << CI->getZExtValue() << 'u';
847 Out << CI->getSExtValue();
848 if (Ty->getPrimitiveSizeInBits() > 32)
855 switch (CPV->getType()->getTypeID()) {
856 case Type::FloatTyID:
857 case Type::DoubleTyID: {
858 ConstantFP *FPC = cast<ConstantFP>(CPV);
859 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
860 if (I != FPConstantMap.end()) {
861 // Because of FP precision problems we must load from a stack allocated
862 // value that holds the value in hex.
863 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
864 << "*)&FPConstant" << I->second << ')';
866 if (IsNAN(FPC->getValue())) {
869 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
871 const unsigned long QuietNaN = 0x7ff8UL;
872 //const unsigned long SignalNaN = 0x7ff4UL;
874 // We need to grab the first part of the FP #
877 uint64_t ll = DoubleToBits(FPC->getValue());
878 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
880 std::string Num(&Buffer[0], &Buffer[6]);
881 unsigned long Val = strtoul(Num.c_str(), 0, 16);
883 if (FPC->getType() == Type::FloatTy)
884 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
885 << Buffer << "\") /*nan*/ ";
887 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
888 << Buffer << "\") /*nan*/ ";
889 } else if (IsInf(FPC->getValue())) {
891 if (FPC->getValue() < 0) Out << '-';
892 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
896 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
897 // Print out the constant as a floating point number.
899 sprintf(Buffer, "%a", FPC->getValue());
902 Num = ftostr(FPC->getValue());
910 case Type::ArrayTyID:
911 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
912 const ArrayType *AT = cast<ArrayType>(CPV->getType());
914 if (AT->getNumElements()) {
916 Constant *CZ = Constant::getNullValue(AT->getElementType());
918 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
925 printConstantArray(cast<ConstantArray>(CPV));
929 case Type::VectorTyID:
930 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
931 const VectorType *AT = cast<VectorType>(CPV->getType());
933 if (AT->getNumElements()) {
935 Constant *CZ = Constant::getNullValue(AT->getElementType());
937 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
944 printConstantVector(cast<ConstantVector>(CPV));
948 case Type::StructTyID:
949 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
950 const StructType *ST = cast<StructType>(CPV->getType());
952 if (ST->getNumElements()) {
954 printConstant(Constant::getNullValue(ST->getElementType(0)));
955 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
957 printConstant(Constant::getNullValue(ST->getElementType(i)));
963 if (CPV->getNumOperands()) {
965 printConstant(cast<Constant>(CPV->getOperand(0)));
966 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
968 printConstant(cast<Constant>(CPV->getOperand(i)));
975 case Type::PointerTyID:
976 if (isa<ConstantPointerNull>(CPV)) {
978 printType(Out, CPV->getType()); // sign doesn't matter
979 Out << ")/*NULL*/0)";
981 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
987 cerr << "Unknown constant type: " << *CPV << "\n";
992 // Some constant expressions need to be casted back to the original types
993 // because their operands were casted to the expected type. This function takes
994 // care of detecting that case and printing the cast for the ConstantExpr.
995 bool CWriter::printConstExprCast(const ConstantExpr* CE) {
996 bool NeedsExplicitCast = false;
997 const Type *Ty = CE->getOperand(0)->getType();
998 bool TypeIsSigned = false;
999 switch (CE->getOpcode()) {
1000 case Instruction::LShr:
1001 case Instruction::URem:
1002 case Instruction::UDiv: NeedsExplicitCast = true; break;
1003 case Instruction::AShr:
1004 case Instruction::SRem:
1005 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1006 case Instruction::SExt:
1008 NeedsExplicitCast = true;
1009 TypeIsSigned = true;
1011 case Instruction::ZExt:
1012 case Instruction::Trunc:
1013 case Instruction::FPTrunc:
1014 case Instruction::FPExt:
1015 case Instruction::UIToFP:
1016 case Instruction::SIToFP:
1017 case Instruction::FPToUI:
1018 case Instruction::FPToSI:
1019 case Instruction::PtrToInt:
1020 case Instruction::IntToPtr:
1021 case Instruction::BitCast:
1023 NeedsExplicitCast = true;
1027 if (NeedsExplicitCast) {
1029 if (Ty->isInteger() && Ty != Type::Int1Ty)
1030 printSimpleType(Out, Ty, TypeIsSigned);
1032 printType(Out, Ty); // not integer, sign doesn't matter
1035 return NeedsExplicitCast;
1038 // Print a constant assuming that it is the operand for a given Opcode. The
1039 // opcodes that care about sign need to cast their operands to the expected
1040 // type before the operation proceeds. This function does the casting.
1041 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1043 // Extract the operand's type, we'll need it.
1044 const Type* OpTy = CPV->getType();
1046 // Indicate whether to do the cast or not.
1047 bool shouldCast = false;
1048 bool typeIsSigned = false;
1050 // Based on the Opcode for which this Constant is being written, determine
1051 // the new type to which the operand should be casted by setting the value
1052 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1056 // for most instructions, it doesn't matter
1058 case Instruction::LShr:
1059 case Instruction::UDiv:
1060 case Instruction::URem:
1063 case Instruction::AShr:
1064 case Instruction::SDiv:
1065 case Instruction::SRem:
1067 typeIsSigned = true;
1071 // Write out the casted constant if we should, otherwise just write the
1075 printSimpleType(Out, OpTy, typeIsSigned);
1083 void CWriter::writeOperandInternal(Value *Operand) {
1084 if (Instruction *I = dyn_cast<Instruction>(Operand))
1085 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1086 // Should we inline this instruction to build a tree?
1093 Constant* CPV = dyn_cast<Constant>(Operand);
1094 if (CPV && !isa<GlobalValue>(CPV)) {
1097 Out << Mang->getValueName(Operand);
1101 void CWriter::writeOperandRaw(Value *Operand) {
1102 Constant* CPV = dyn_cast<Constant>(Operand);
1103 if (CPV && !isa<GlobalValue>(CPV)) {
1106 Out << Mang->getValueName(Operand);
1110 void CWriter::writeOperand(Value *Operand) {
1111 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1112 Out << "(&"; // Global variables are referenced as their addresses by llvm
1114 writeOperandInternal(Operand);
1116 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1120 // Some instructions need to have their result value casted back to the
1121 // original types because their operands were casted to the expected type.
1122 // This function takes care of detecting that case and printing the cast
1123 // for the Instruction.
1124 bool CWriter::writeInstructionCast(const Instruction &I) {
1125 const Type *Ty = I.getOperand(0)->getType();
1126 switch (I.getOpcode()) {
1127 case Instruction::LShr:
1128 case Instruction::URem:
1129 case Instruction::UDiv:
1131 printSimpleType(Out, Ty, false);
1134 case Instruction::AShr:
1135 case Instruction::SRem:
1136 case Instruction::SDiv:
1138 printSimpleType(Out, Ty, true);
1146 // Write the operand with a cast to another type based on the Opcode being used.
1147 // This will be used in cases where an instruction has specific type
1148 // requirements (usually signedness) for its operands.
1149 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1151 // Extract the operand's type, we'll need it.
1152 const Type* OpTy = Operand->getType();
1154 // Indicate whether to do the cast or not.
1155 bool shouldCast = false;
1157 // Indicate whether the cast should be to a signed type or not.
1158 bool castIsSigned = false;
1160 // Based on the Opcode for which this Operand is being written, determine
1161 // the new type to which the operand should be casted by setting the value
1162 // of OpTy. If we change OpTy, also set shouldCast to true.
1165 // for most instructions, it doesn't matter
1167 case Instruction::LShr:
1168 case Instruction::UDiv:
1169 case Instruction::URem: // Cast to unsigned first
1171 castIsSigned = false;
1173 case Instruction::AShr:
1174 case Instruction::SDiv:
1175 case Instruction::SRem: // Cast to signed first
1177 castIsSigned = true;
1181 // Write out the casted operand if we should, otherwise just write the
1185 printSimpleType(Out, OpTy, castIsSigned);
1187 writeOperand(Operand);
1190 writeOperand(Operand);
1193 // Write the operand with a cast to another type based on the icmp predicate
1195 void CWriter::writeOperandWithCast(Value* Operand, ICmpInst::Predicate predicate) {
1197 // Extract the operand's type, we'll need it.
1198 const Type* OpTy = Operand->getType();
1200 // Indicate whether to do the cast or not.
1201 bool shouldCast = false;
1203 // Indicate whether the cast should be to a signed type or not.
1204 bool castIsSigned = false;
1206 // Based on the Opcode for which this Operand is being written, determine
1207 // the new type to which the operand should be casted by setting the value
1208 // of OpTy. If we change OpTy, also set shouldCast to true.
1209 switch (predicate) {
1211 // for eq and ne, it doesn't matter
1213 case ICmpInst::ICMP_UGT:
1214 case ICmpInst::ICMP_UGE:
1215 case ICmpInst::ICMP_ULT:
1216 case ICmpInst::ICMP_ULE:
1219 case ICmpInst::ICMP_SGT:
1220 case ICmpInst::ICMP_SGE:
1221 case ICmpInst::ICMP_SLT:
1222 case ICmpInst::ICMP_SLE:
1224 castIsSigned = true;
1228 // Write out the casted operand if we should, otherwise just write the
1232 if (OpTy->isInteger() && OpTy != Type::Int1Ty)
1233 printSimpleType(Out, OpTy, castIsSigned);
1235 printType(Out, OpTy); // not integer, sign doesn't matter
1237 writeOperand(Operand);
1240 writeOperand(Operand);
1243 // generateCompilerSpecificCode - This is where we add conditional compilation
1244 // directives to cater to specific compilers as need be.
1246 static void generateCompilerSpecificCode(std::ostream& Out) {
1247 // Alloca is hard to get, and we don't want to include stdlib.h here.
1248 Out << "/* get a declaration for alloca */\n"
1249 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1250 << "extern void *_alloca(unsigned long);\n"
1251 << "#define alloca(x) _alloca(x)\n"
1252 << "#elif defined(__APPLE__)\n"
1253 << "extern void *__builtin_alloca(unsigned long);\n"
1254 << "#define alloca(x) __builtin_alloca(x)\n"
1255 << "#define longjmp _longjmp\n"
1256 << "#define setjmp _setjmp\n"
1257 << "#elif defined(__sun__)\n"
1258 << "#if defined(__sparcv9)\n"
1259 << "extern void *__builtin_alloca(unsigned long);\n"
1261 << "extern void *__builtin_alloca(unsigned int);\n"
1263 << "#define alloca(x) __builtin_alloca(x)\n"
1264 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
1265 << "#define alloca(x) __builtin_alloca(x)\n"
1266 << "#elif !defined(_MSC_VER)\n"
1267 << "#include <alloca.h>\n"
1270 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1271 // If we aren't being compiled with GCC, just drop these attributes.
1272 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1273 << "#define __attribute__(X)\n"
1276 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1277 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1278 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1279 << "#elif defined(__GNUC__)\n"
1280 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1282 << "#define __EXTERNAL_WEAK__\n"
1285 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1286 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1287 << "#define __ATTRIBUTE_WEAK__\n"
1288 << "#elif defined(__GNUC__)\n"
1289 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1291 << "#define __ATTRIBUTE_WEAK__\n"
1294 // Add hidden visibility support. FIXME: APPLE_CC?
1295 Out << "#if defined(__GNUC__)\n"
1296 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1299 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1300 // From the GCC documentation:
1302 // double __builtin_nan (const char *str)
1304 // This is an implementation of the ISO C99 function nan.
1306 // Since ISO C99 defines this function in terms of strtod, which we do
1307 // not implement, a description of the parsing is in order. The string is
1308 // parsed as by strtol; that is, the base is recognized by leading 0 or
1309 // 0x prefixes. The number parsed is placed in the significand such that
1310 // the least significant bit of the number is at the least significant
1311 // bit of the significand. The number is truncated to fit the significand
1312 // field provided. The significand is forced to be a quiet NaN.
1314 // This function, if given a string literal, is evaluated early enough
1315 // that it is considered a compile-time constant.
1317 // float __builtin_nanf (const char *str)
1319 // Similar to __builtin_nan, except the return type is float.
1321 // double __builtin_inf (void)
1323 // Similar to __builtin_huge_val, except a warning is generated if the
1324 // target floating-point format does not support infinities. This
1325 // function is suitable for implementing the ISO C99 macro INFINITY.
1327 // float __builtin_inff (void)
1329 // Similar to __builtin_inf, except the return type is float.
1330 Out << "#ifdef __GNUC__\n"
1331 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1332 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1333 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1334 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1335 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1336 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1337 << "#define LLVM_PREFETCH(addr,rw,locality) "
1338 "__builtin_prefetch(addr,rw,locality)\n"
1339 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1340 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1341 << "#define LLVM_ASM __asm__\n"
1343 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1344 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1345 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1346 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1347 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1348 << "#define LLVM_INFF 0.0F /* Float */\n"
1349 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1350 << "#define __ATTRIBUTE_CTOR__\n"
1351 << "#define __ATTRIBUTE_DTOR__\n"
1352 << "#define LLVM_ASM(X)\n"
1355 // Output target-specific code that should be inserted into main.
1356 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1357 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
1358 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
1359 << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
1360 << "defined(__x86_64__)\n"
1361 << "#undef CODE_FOR_MAIN\n"
1362 << "#define CODE_FOR_MAIN() \\\n"
1363 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
1364 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
1365 << "#endif\n#endif\n";
1369 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1370 /// the StaticTors set.
1371 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1372 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1373 if (!InitList) return;
1375 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1376 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1377 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1379 if (CS->getOperand(1)->isNullValue())
1380 return; // Found a null terminator, exit printing.
1381 Constant *FP = CS->getOperand(1);
1382 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1384 FP = CE->getOperand(0);
1385 if (Function *F = dyn_cast<Function>(FP))
1386 StaticTors.insert(F);
1390 enum SpecialGlobalClass {
1392 GlobalCtors, GlobalDtors,
1396 /// getGlobalVariableClass - If this is a global that is specially recognized
1397 /// by LLVM, return a code that indicates how we should handle it.
1398 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1399 // If this is a global ctors/dtors list, handle it now.
1400 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1401 if (GV->getName() == "llvm.global_ctors")
1403 else if (GV->getName() == "llvm.global_dtors")
1407 // Otherwise, it it is other metadata, don't print it. This catches things
1408 // like debug information.
1409 if (GV->getSection() == "llvm.metadata")
1416 bool CWriter::doInitialization(Module &M) {
1420 TD = new TargetData(&M);
1421 IL = new IntrinsicLowering(*TD);
1422 IL->AddPrototypes(M);
1424 // Ensure that all structure types have names...
1425 Mang = new Mangler(M);
1426 Mang->markCharUnacceptable('.');
1428 // Keep track of which functions are static ctors/dtors so they can have
1429 // an attribute added to their prototypes.
1430 std::set<Function*> StaticCtors, StaticDtors;
1431 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1433 switch (getGlobalVariableClass(I)) {
1436 FindStaticTors(I, StaticCtors);
1439 FindStaticTors(I, StaticDtors);
1444 // get declaration for alloca
1445 Out << "/* Provide Declarations */\n";
1446 Out << "#include <stdarg.h>\n"; // Varargs support
1447 Out << "#include <setjmp.h>\n"; // Unwind support
1448 generateCompilerSpecificCode(Out);
1450 // Provide a definition for `bool' if not compiling with a C++ compiler.
1452 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1454 << "\n\n/* Support for floating point constants */\n"
1455 << "typedef unsigned long long ConstantDoubleTy;\n"
1456 << "typedef unsigned int ConstantFloatTy;\n"
1458 << "\n\n/* Global Declarations */\n";
1460 // First output all the declarations for the program, because C requires
1461 // Functions & globals to be declared before they are used.
1464 // Loop over the symbol table, emitting all named constants...
1465 printModuleTypes(M.getTypeSymbolTable());
1467 // Global variable declarations...
1468 if (!M.global_empty()) {
1469 Out << "\n/* External Global Variable Declarations */\n";
1470 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1472 if (I->hasExternalLinkage()) {
1474 printType(Out, I->getType()->getElementType(), false,
1475 Mang->getValueName(I));
1477 } else if (I->hasDLLImportLinkage()) {
1478 Out << "__declspec(dllimport) ";
1479 printType(Out, I->getType()->getElementType(), false,
1480 Mang->getValueName(I));
1482 } else if (I->hasExternalWeakLinkage()) {
1484 printType(Out, I->getType()->getElementType(), false,
1485 Mang->getValueName(I));
1486 Out << " __EXTERNAL_WEAK__ ;\n";
1491 // Function declarations
1492 Out << "\n/* Function Declarations */\n";
1493 Out << "double fmod(double, double);\n"; // Support for FP rem
1494 Out << "float fmodf(float, float);\n";
1496 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1497 // Don't print declarations for intrinsic functions.
1498 if (!I->getIntrinsicID() && I->getName() != "setjmp" &&
1499 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1500 if (I->hasExternalWeakLinkage())
1502 printFunctionSignature(I, true);
1503 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1504 Out << " __ATTRIBUTE_WEAK__";
1505 if (I->hasExternalWeakLinkage())
1506 Out << " __EXTERNAL_WEAK__";
1507 if (StaticCtors.count(I))
1508 Out << " __ATTRIBUTE_CTOR__";
1509 if (StaticDtors.count(I))
1510 Out << " __ATTRIBUTE_DTOR__";
1511 if (I->hasHiddenVisibility())
1512 Out << " __HIDDEN__";
1514 if (I->hasName() && I->getName()[0] == 1)
1515 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1521 // Output the global variable declarations
1522 if (!M.global_empty()) {
1523 Out << "\n\n/* Global Variable Declarations */\n";
1524 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1526 if (!I->isDeclaration()) {
1527 // Ignore special globals, such as debug info.
1528 if (getGlobalVariableClass(I))
1531 if (I->hasInternalLinkage())
1535 printType(Out, I->getType()->getElementType(), false,
1536 Mang->getValueName(I));
1538 if (I->hasLinkOnceLinkage())
1539 Out << " __attribute__((common))";
1540 else if (I->hasWeakLinkage())
1541 Out << " __ATTRIBUTE_WEAK__";
1542 else if (I->hasExternalWeakLinkage())
1543 Out << " __EXTERNAL_WEAK__";
1544 if (I->hasHiddenVisibility())
1545 Out << " __HIDDEN__";
1550 // Output the global variable definitions and contents...
1551 if (!M.global_empty()) {
1552 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1553 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1555 if (!I->isDeclaration()) {
1556 // Ignore special globals, such as debug info.
1557 if (getGlobalVariableClass(I))
1560 if (I->hasInternalLinkage())
1562 else if (I->hasDLLImportLinkage())
1563 Out << "__declspec(dllimport) ";
1564 else if (I->hasDLLExportLinkage())
1565 Out << "__declspec(dllexport) ";
1567 printType(Out, I->getType()->getElementType(), false,
1568 Mang->getValueName(I));
1569 if (I->hasLinkOnceLinkage())
1570 Out << " __attribute__((common))";
1571 else if (I->hasWeakLinkage())
1572 Out << " __ATTRIBUTE_WEAK__";
1574 if (I->hasHiddenVisibility())
1575 Out << " __HIDDEN__";
1577 // If the initializer is not null, emit the initializer. If it is null,
1578 // we try to avoid emitting large amounts of zeros. The problem with
1579 // this, however, occurs when the variable has weak linkage. In this
1580 // case, the assembler will complain about the variable being both weak
1581 // and common, so we disable this optimization.
1582 if (!I->getInitializer()->isNullValue()) {
1584 writeOperand(I->getInitializer());
1585 } else if (I->hasWeakLinkage()) {
1586 // We have to specify an initializer, but it doesn't have to be
1587 // complete. If the value is an aggregate, print out { 0 }, and let
1588 // the compiler figure out the rest of the zeros.
1590 if (isa<StructType>(I->getInitializer()->getType()) ||
1591 isa<ArrayType>(I->getInitializer()->getType()) ||
1592 isa<VectorType>(I->getInitializer()->getType())) {
1595 // Just print it out normally.
1596 writeOperand(I->getInitializer());
1604 Out << "\n\n/* Function Bodies */\n";
1606 // Emit some helper functions for dealing with FCMP instruction's
1608 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1609 Out << "return X == X && Y == Y; }\n";
1610 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1611 Out << "return X != X || Y != Y; }\n";
1612 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
1613 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
1614 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
1615 Out << "return X != Y; }\n";
1616 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
1617 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
1618 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
1619 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
1620 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
1621 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
1622 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
1623 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
1624 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
1625 Out << "return X == Y ; }\n";
1626 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
1627 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
1628 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
1629 Out << "return X < Y ; }\n";
1630 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
1631 Out << "return X > Y ; }\n";
1632 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
1633 Out << "return X <= Y ; }\n";
1634 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
1635 Out << "return X >= Y ; }\n";
1640 /// Output all floating point constants that cannot be printed accurately...
1641 void CWriter::printFloatingPointConstants(Function &F) {
1642 // Scan the module for floating point constants. If any FP constant is used
1643 // in the function, we want to redirect it here so that we do not depend on
1644 // the precision of the printed form, unless the printed form preserves
1647 static unsigned FPCounter = 0;
1648 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1650 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1651 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1652 !FPConstantMap.count(FPC)) {
1653 double Val = FPC->getValue();
1655 FPConstantMap[FPC] = FPCounter; // Number the FP constants
1657 if (FPC->getType() == Type::DoubleTy) {
1658 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1659 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
1660 << "ULL; /* " << Val << " */\n";
1661 } else if (FPC->getType() == Type::FloatTy) {
1662 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1663 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
1664 << "U; /* " << Val << " */\n";
1666 assert(0 && "Unknown float type!");
1673 /// printSymbolTable - Run through symbol table looking for type names. If a
1674 /// type name is found, emit its declaration...
1676 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
1677 Out << "/* Helper union for bitcasts */\n";
1678 Out << "typedef union {\n";
1679 Out << " unsigned int Int32;\n";
1680 Out << " unsigned long long Int64;\n";
1681 Out << " float Float;\n";
1682 Out << " double Double;\n";
1683 Out << "} llvmBitCastUnion;\n";
1685 // We are only interested in the type plane of the symbol table.
1686 TypeSymbolTable::const_iterator I = TST.begin();
1687 TypeSymbolTable::const_iterator End = TST.end();
1689 // If there are no type names, exit early.
1690 if (I == End) return;
1692 // Print out forward declarations for structure types before anything else!
1693 Out << "/* Structure forward decls */\n";
1694 for (; I != End; ++I) {
1695 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1696 Out << Name << ";\n";
1697 TypeNames.insert(std::make_pair(I->second, Name));
1702 // Now we can print out typedefs. Above, we guaranteed that this can only be
1703 // for struct or opaque types.
1704 Out << "/* Typedefs */\n";
1705 for (I = TST.begin(); I != End; ++I) {
1706 std::string Name = "l_" + Mang->makeNameProper(I->first);
1708 printType(Out, I->second, false, Name);
1714 // Keep track of which structures have been printed so far...
1715 std::set<const StructType *> StructPrinted;
1717 // Loop over all structures then push them into the stack so they are
1718 // printed in the correct order.
1720 Out << "/* Structure contents */\n";
1721 for (I = TST.begin(); I != End; ++I)
1722 if (const StructType *STy = dyn_cast<StructType>(I->second))
1723 // Only print out used types!
1724 printContainedStructs(STy, StructPrinted);
1727 // Push the struct onto the stack and recursively push all structs
1728 // this one depends on.
1730 // TODO: Make this work properly with vector types
1732 void CWriter::printContainedStructs(const Type *Ty,
1733 std::set<const StructType*> &StructPrinted){
1734 // Don't walk through pointers.
1735 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
1737 // Print all contained types first.
1738 for (Type::subtype_iterator I = Ty->subtype_begin(),
1739 E = Ty->subtype_end(); I != E; ++I)
1740 printContainedStructs(*I, StructPrinted);
1742 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1743 // Check to see if we have already printed this struct.
1744 if (StructPrinted.insert(STy).second) {
1745 // Print structure type out.
1746 std::string Name = TypeNames[STy];
1747 printType(Out, STy, false, Name, true);
1753 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1754 /// isStructReturn - Should this function actually return a struct by-value?
1755 bool isStructReturn = F->getFunctionType()->isStructReturn();
1757 if (F->hasInternalLinkage()) Out << "static ";
1758 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1759 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
1760 switch (F->getCallingConv()) {
1761 case CallingConv::X86_StdCall:
1762 Out << "__stdcall ";
1764 case CallingConv::X86_FastCall:
1765 Out << "__fastcall ";
1769 // Loop over the arguments, printing them...
1770 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1772 std::stringstream FunctionInnards;
1774 // Print out the name...
1775 FunctionInnards << Mang->getValueName(F) << '(';
1777 bool PrintedArg = false;
1778 if (!F->isDeclaration()) {
1779 if (!F->arg_empty()) {
1780 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1782 // If this is a struct-return function, don't print the hidden
1783 // struct-return argument.
1784 if (isStructReturn) {
1785 assert(I != E && "Invalid struct return function!");
1789 std::string ArgName;
1791 for (; I != E; ++I) {
1792 if (PrintedArg) FunctionInnards << ", ";
1793 if (I->hasName() || !Prototype)
1794 ArgName = Mang->getValueName(I);
1797 printType(FunctionInnards, I->getType(),
1798 /*isSigned=*/FT->paramHasAttr(Idx, FunctionType::SExtAttribute),
1805 // Loop over the arguments, printing them.
1806 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1808 // If this is a struct-return function, don't print the hidden
1809 // struct-return argument.
1810 if (isStructReturn) {
1811 assert(I != E && "Invalid struct return function!");
1816 for (; I != E; ++I) {
1817 if (PrintedArg) FunctionInnards << ", ";
1818 printType(FunctionInnards, *I,
1819 /*isSigned=*/FT->paramHasAttr(Idx, FunctionType::SExtAttribute));
1825 // Finish printing arguments... if this is a vararg function, print the ...,
1826 // unless there are no known types, in which case, we just emit ().
1828 if (FT->isVarArg() && PrintedArg) {
1829 if (PrintedArg) FunctionInnards << ", ";
1830 FunctionInnards << "..."; // Output varargs portion of signature!
1831 } else if (!FT->isVarArg() && !PrintedArg) {
1832 FunctionInnards << "void"; // ret() -> ret(void) in C.
1834 FunctionInnards << ')';
1836 // Get the return tpe for the function.
1838 if (!isStructReturn)
1839 RetTy = F->getReturnType();
1841 // If this is a struct-return function, print the struct-return type.
1842 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1845 // Print out the return type and the signature built above.
1846 printType(Out, RetTy,
1847 /*isSigned=*/FT->paramHasAttr(0, FunctionType::SExtAttribute),
1848 FunctionInnards.str());
1851 static inline bool isFPIntBitCast(const Instruction &I) {
1852 if (!isa<BitCastInst>(I))
1854 const Type *SrcTy = I.getOperand(0)->getType();
1855 const Type *DstTy = I.getType();
1856 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
1857 (DstTy->isFloatingPoint() && SrcTy->isInteger());
1860 void CWriter::printFunction(Function &F) {
1861 /// isStructReturn - Should this function actually return a struct by-value?
1862 bool isStructReturn = F.getFunctionType()->isStructReturn();
1864 printFunctionSignature(&F, false);
1867 // If this is a struct return function, handle the result with magic.
1868 if (isStructReturn) {
1869 const Type *StructTy =
1870 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1872 printType(Out, StructTy, false, "StructReturn");
1873 Out << "; /* Struct return temporary */\n";
1876 printType(Out, F.arg_begin()->getType(), false,
1877 Mang->getValueName(F.arg_begin()));
1878 Out << " = &StructReturn;\n";
1881 bool PrintedVar = false;
1883 // print local variable information for the function
1884 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
1885 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1887 printType(Out, AI->getAllocatedType(), false, Mang->getValueName(AI));
1888 Out << "; /* Address-exposed local */\n";
1890 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1892 printType(Out, I->getType(), false, Mang->getValueName(&*I));
1895 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1897 printType(Out, I->getType(), false,
1898 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
1903 // We need a temporary for the BitCast to use so it can pluck a value out
1904 // of a union to do the BitCast. This is separate from the need for a
1905 // variable to hold the result of the BitCast.
1906 if (isFPIntBitCast(*I)) {
1907 Out << " llvmBitCastUnion " << Mang->getValueName(&*I)
1908 << "__BITCAST_TEMPORARY;\n";
1916 if (F.hasExternalLinkage() && F.getName() == "main")
1917 Out << " CODE_FOR_MAIN();\n";
1919 // print the basic blocks
1920 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1921 if (Loop *L = LI->getLoopFor(BB)) {
1922 if (L->getHeader() == BB && L->getParentLoop() == 0)
1925 printBasicBlock(BB);
1932 void CWriter::printLoop(Loop *L) {
1933 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1934 << "' to make GCC happy */\n";
1935 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1936 BasicBlock *BB = L->getBlocks()[i];
1937 Loop *BBLoop = LI->getLoopFor(BB);
1939 printBasicBlock(BB);
1940 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1943 Out << " } while (1); /* end of syntactic loop '"
1944 << L->getHeader()->getName() << "' */\n";
1947 void CWriter::printBasicBlock(BasicBlock *BB) {
1949 // Don't print the label for the basic block if there are no uses, or if
1950 // the only terminator use is the predecessor basic block's terminator.
1951 // We have to scan the use list because PHI nodes use basic blocks too but
1952 // do not require a label to be generated.
1954 bool NeedsLabel = false;
1955 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1956 if (isGotoCodeNecessary(*PI, BB)) {
1961 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1963 // Output all of the instructions in the basic block...
1964 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1966 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1967 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
1976 // Don't emit prefix or suffix for the terminator...
1977 visit(*BB->getTerminator());
1981 // Specific Instruction type classes... note that all of the casts are
1982 // necessary because we use the instruction classes as opaque types...
1984 void CWriter::visitReturnInst(ReturnInst &I) {
1985 // If this is a struct return function, return the temporary struct.
1986 bool isStructReturn = I.getParent()->getParent()->
1987 getFunctionType()->isStructReturn();
1989 if (isStructReturn) {
1990 Out << " return StructReturn;\n";
1994 // Don't output a void return if this is the last basic block in the function
1995 if (I.getNumOperands() == 0 &&
1996 &*--I.getParent()->getParent()->end() == I.getParent() &&
1997 !I.getParent()->size() == 1) {
2002 if (I.getNumOperands()) {
2004 writeOperand(I.getOperand(0));
2009 void CWriter::visitSwitchInst(SwitchInst &SI) {
2012 writeOperand(SI.getOperand(0));
2013 Out << ") {\n default:\n";
2014 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2015 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2017 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2019 writeOperand(SI.getOperand(i));
2021 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2022 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2023 printBranchToBlock(SI.getParent(), Succ, 2);
2024 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
2030 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2031 Out << " /*UNREACHABLE*/;\n";
2034 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2035 /// FIXME: This should be reenabled, but loop reordering safe!!
2038 if (next(Function::iterator(From)) != Function::iterator(To))
2039 return true; // Not the direct successor, we need a goto.
2041 //isa<SwitchInst>(From->getTerminator())
2043 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2048 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2049 BasicBlock *Successor,
2051 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2052 PHINode *PN = cast<PHINode>(I);
2053 // Now we have to do the printing.
2054 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2055 if (!isa<UndefValue>(IV)) {
2056 Out << std::string(Indent, ' ');
2057 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
2059 Out << "; /* for PHI node */\n";
2064 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2066 if (isGotoCodeNecessary(CurBB, Succ)) {
2067 Out << std::string(Indent, ' ') << " goto ";
2073 // Branch instruction printing - Avoid printing out a branch to a basic block
2074 // that immediately succeeds the current one.
2076 void CWriter::visitBranchInst(BranchInst &I) {
2078 if (I.isConditional()) {
2079 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2081 writeOperand(I.getCondition());
2084 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2085 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2087 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2088 Out << " } else {\n";
2089 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2090 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2093 // First goto not necessary, assume second one is...
2095 writeOperand(I.getCondition());
2098 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2099 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2104 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2105 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2110 // PHI nodes get copied into temporary values at the end of predecessor basic
2111 // blocks. We now need to copy these temporary values into the REAL value for
2113 void CWriter::visitPHINode(PHINode &I) {
2115 Out << "__PHI_TEMPORARY";
2119 void CWriter::visitBinaryOperator(Instruction &I) {
2120 // binary instructions, shift instructions, setCond instructions.
2121 assert(!isa<PointerType>(I.getType()));
2123 // We must cast the results of binary operations which might be promoted.
2124 bool needsCast = false;
2125 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
2126 || (I.getType() == Type::FloatTy)) {
2129 printType(Out, I.getType(), false);
2133 // If this is a negation operation, print it out as such. For FP, we don't
2134 // want to print "-0.0 - X".
2135 if (BinaryOperator::isNeg(&I)) {
2137 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2139 } else if (I.getOpcode() == Instruction::FRem) {
2140 // Output a call to fmod/fmodf instead of emitting a%b
2141 if (I.getType() == Type::FloatTy)
2145 writeOperand(I.getOperand(0));
2147 writeOperand(I.getOperand(1));
2151 // Write out the cast of the instruction's value back to the proper type
2153 bool NeedsClosingParens = writeInstructionCast(I);
2155 // Certain instructions require the operand to be forced to a specific type
2156 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2157 // below for operand 1
2158 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2160 switch (I.getOpcode()) {
2161 case Instruction::Add: Out << " + "; break;
2162 case Instruction::Sub: Out << " - "; break;
2163 case Instruction::Mul: Out << " * "; break;
2164 case Instruction::URem:
2165 case Instruction::SRem:
2166 case Instruction::FRem: Out << " % "; break;
2167 case Instruction::UDiv:
2168 case Instruction::SDiv:
2169 case Instruction::FDiv: Out << " / "; break;
2170 case Instruction::And: Out << " & "; break;
2171 case Instruction::Or: Out << " | "; break;
2172 case Instruction::Xor: Out << " ^ "; break;
2173 case Instruction::Shl : Out << " << "; break;
2174 case Instruction::LShr:
2175 case Instruction::AShr: Out << " >> "; break;
2176 default: cerr << "Invalid operator type!" << I; abort();
2179 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2180 if (NeedsClosingParens)
2189 void CWriter::visitICmpInst(ICmpInst &I) {
2190 // We must cast the results of icmp which might be promoted.
2191 bool needsCast = false;
2193 // Write out the cast of the instruction's value back to the proper type
2195 bool NeedsClosingParens = writeInstructionCast(I);
2197 // Certain icmp predicate require the operand to be forced to a specific type
2198 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2199 // below for operand 1
2200 writeOperandWithCast(I.getOperand(0), I.getPredicate());
2202 switch (I.getPredicate()) {
2203 case ICmpInst::ICMP_EQ: Out << " == "; break;
2204 case ICmpInst::ICMP_NE: Out << " != "; break;
2205 case ICmpInst::ICMP_ULE:
2206 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2207 case ICmpInst::ICMP_UGE:
2208 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2209 case ICmpInst::ICMP_ULT:
2210 case ICmpInst::ICMP_SLT: Out << " < "; break;
2211 case ICmpInst::ICMP_UGT:
2212 case ICmpInst::ICMP_SGT: Out << " > "; break;
2213 default: cerr << "Invalid icmp predicate!" << I; abort();
2216 writeOperandWithCast(I.getOperand(1), I.getPredicate());
2217 if (NeedsClosingParens)
2225 void CWriter::visitFCmpInst(FCmpInst &I) {
2226 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2230 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2236 switch (I.getPredicate()) {
2237 default: assert(0 && "Illegal FCmp predicate");
2238 case FCmpInst::FCMP_ORD: op = "ord"; break;
2239 case FCmpInst::FCMP_UNO: op = "uno"; break;
2240 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2241 case FCmpInst::FCMP_UNE: op = "une"; break;
2242 case FCmpInst::FCMP_ULT: op = "ult"; break;
2243 case FCmpInst::FCMP_ULE: op = "ule"; break;
2244 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2245 case FCmpInst::FCMP_UGE: op = "uge"; break;
2246 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2247 case FCmpInst::FCMP_ONE: op = "one"; break;
2248 case FCmpInst::FCMP_OLT: op = "olt"; break;
2249 case FCmpInst::FCMP_OLE: op = "ole"; break;
2250 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2251 case FCmpInst::FCMP_OGE: op = "oge"; break;
2254 Out << "llvm_fcmp_" << op << "(";
2255 // Write the first operand
2256 writeOperand(I.getOperand(0));
2258 // Write the second operand
2259 writeOperand(I.getOperand(1));
2263 static const char * getFloatBitCastField(const Type *Ty) {
2264 switch (Ty->getTypeID()) {
2265 default: assert(0 && "Invalid Type");
2266 case Type::FloatTyID: return "Float";
2267 case Type::DoubleTyID: return "Double";
2268 case Type::IntegerTyID: {
2269 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2278 void CWriter::visitCastInst(CastInst &I) {
2279 const Type *DstTy = I.getType();
2280 const Type *SrcTy = I.getOperand(0)->getType();
2282 if (isFPIntBitCast(I)) {
2283 // These int<->float and long<->double casts need to be handled specially
2284 Out << Mang->getValueName(&I) << "__BITCAST_TEMPORARY."
2285 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2286 writeOperand(I.getOperand(0));
2287 Out << ", " << Mang->getValueName(&I) << "__BITCAST_TEMPORARY."
2288 << getFloatBitCastField(I.getType());
2290 printCast(I.getOpcode(), SrcTy, DstTy);
2291 if (I.getOpcode() == Instruction::SExt && SrcTy == Type::Int1Ty) {
2292 // Make sure we really get a sext from bool by subtracing the bool from 0
2295 writeOperand(I.getOperand(0));
2296 if (DstTy == Type::Int1Ty &&
2297 (I.getOpcode() == Instruction::Trunc ||
2298 I.getOpcode() == Instruction::FPToUI ||
2299 I.getOpcode() == Instruction::FPToSI ||
2300 I.getOpcode() == Instruction::PtrToInt)) {
2301 // Make sure we really get a trunc to bool by anding the operand with 1
2308 void CWriter::visitSelectInst(SelectInst &I) {
2310 writeOperand(I.getCondition());
2312 writeOperand(I.getTrueValue());
2314 writeOperand(I.getFalseValue());
2319 void CWriter::lowerIntrinsics(Function &F) {
2320 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2321 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2322 if (CallInst *CI = dyn_cast<CallInst>(I++))
2323 if (Function *F = CI->getCalledFunction())
2324 switch (F->getIntrinsicID()) {
2325 case Intrinsic::not_intrinsic:
2326 case Intrinsic::vastart:
2327 case Intrinsic::vacopy:
2328 case Intrinsic::vaend:
2329 case Intrinsic::returnaddress:
2330 case Intrinsic::frameaddress:
2331 case Intrinsic::setjmp:
2332 case Intrinsic::longjmp:
2333 case Intrinsic::prefetch:
2334 case Intrinsic::dbg_stoppoint:
2335 case Intrinsic::powi_f32:
2336 case Intrinsic::powi_f64:
2337 // We directly implement these intrinsics
2340 // If this is an intrinsic that directly corresponds to a GCC
2341 // builtin, we handle it.
2342 const char *BuiltinName = "";
2343 #define GET_GCC_BUILTIN_NAME
2344 #include "llvm/Intrinsics.gen"
2345 #undef GET_GCC_BUILTIN_NAME
2346 // If we handle it, don't lower it.
2347 if (BuiltinName[0]) break;
2349 // All other intrinsic calls we must lower.
2350 Instruction *Before = 0;
2351 if (CI != &BB->front())
2352 Before = prior(BasicBlock::iterator(CI));
2354 IL->LowerIntrinsicCall(CI);
2355 if (Before) { // Move iterator to instruction after call
2366 void CWriter::visitCallInst(CallInst &I) {
2367 //check if we have inline asm
2368 if (isInlineAsm(I)) {
2373 bool WroteCallee = false;
2375 // Handle intrinsic function calls first...
2376 if (Function *F = I.getCalledFunction())
2377 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
2380 // If this is an intrinsic that directly corresponds to a GCC
2381 // builtin, we emit it here.
2382 const char *BuiltinName = "";
2383 #define GET_GCC_BUILTIN_NAME
2384 #include "llvm/Intrinsics.gen"
2385 #undef GET_GCC_BUILTIN_NAME
2386 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2392 case Intrinsic::vastart:
2395 Out << "va_start(*(va_list*)";
2396 writeOperand(I.getOperand(1));
2398 // Output the last argument to the enclosing function...
2399 if (I.getParent()->getParent()->arg_empty()) {
2400 cerr << "The C backend does not currently support zero "
2401 << "argument varargs functions, such as '"
2402 << I.getParent()->getParent()->getName() << "'!\n";
2405 writeOperand(--I.getParent()->getParent()->arg_end());
2408 case Intrinsic::vaend:
2409 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2410 Out << "0; va_end(*(va_list*)";
2411 writeOperand(I.getOperand(1));
2414 Out << "va_end(*(va_list*)0)";
2417 case Intrinsic::vacopy:
2419 Out << "va_copy(*(va_list*)";
2420 writeOperand(I.getOperand(1));
2421 Out << ", *(va_list*)";
2422 writeOperand(I.getOperand(2));
2425 case Intrinsic::returnaddress:
2426 Out << "__builtin_return_address(";
2427 writeOperand(I.getOperand(1));
2430 case Intrinsic::frameaddress:
2431 Out << "__builtin_frame_address(";
2432 writeOperand(I.getOperand(1));
2435 case Intrinsic::powi_f32:
2436 case Intrinsic::powi_f64:
2437 Out << "__builtin_powi(";
2438 writeOperand(I.getOperand(1));
2440 writeOperand(I.getOperand(2));
2443 case Intrinsic::setjmp:
2444 Out << "setjmp(*(jmp_buf*)";
2445 writeOperand(I.getOperand(1));
2448 case Intrinsic::longjmp:
2449 Out << "longjmp(*(jmp_buf*)";
2450 writeOperand(I.getOperand(1));
2452 writeOperand(I.getOperand(2));
2455 case Intrinsic::prefetch:
2456 Out << "LLVM_PREFETCH((const void *)";
2457 writeOperand(I.getOperand(1));
2459 writeOperand(I.getOperand(2));
2461 writeOperand(I.getOperand(3));
2464 case Intrinsic::dbg_stoppoint: {
2465 // If we use writeOperand directly we get a "u" suffix which is rejected
2467 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2471 << " \"" << SPI.getDirectory()
2472 << SPI.getFileName() << "\"\n";
2478 Value *Callee = I.getCalledValue();
2480 const PointerType *PTy = cast<PointerType>(Callee->getType());
2481 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2483 // If this is a call to a struct-return function, assign to the first
2484 // parameter instead of passing it to the call.
2485 bool isStructRet = FTy->isStructReturn();
2488 writeOperand(I.getOperand(1));
2492 if (I.isTailCall()) Out << " /*tail*/ ";
2495 // If this is an indirect call to a struct return function, we need to cast
2497 bool NeedsCast = isStructRet && !isa<Function>(Callee);
2499 // GCC is a real PITA. It does not permit codegening casts of functions to
2500 // function pointers if they are in a call (it generates a trap instruction
2501 // instead!). We work around this by inserting a cast to void* in between
2502 // the function and the function pointer cast. Unfortunately, we can't just
2503 // form the constant expression here, because the folder will immediately
2506 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2507 // that void* and function pointers have the same size. :( To deal with this
2508 // in the common case, we handle casts where the number of arguments passed
2511 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2513 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2519 // Ok, just cast the pointer type.
2522 printType(Out, I.getCalledValue()->getType());
2524 printStructReturnPointerFunctionType(Out,
2525 cast<PointerType>(I.getCalledValue()->getType()));
2528 writeOperand(Callee);
2529 if (NeedsCast) Out << ')';
2534 unsigned NumDeclaredParams = FTy->getNumParams();
2536 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2538 if (isStructRet) { // Skip struct return argument.
2543 bool PrintedArg = false;
2545 for (; AI != AE; ++AI, ++ArgNo, ++Idx) {
2546 if (PrintedArg) Out << ", ";
2547 if (ArgNo < NumDeclaredParams &&
2548 (*AI)->getType() != FTy->getParamType(ArgNo)) {
2550 printType(Out, FTy->getParamType(ArgNo),
2551 /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute));
2561 //This converts the llvm constraint string to something gcc is expecting.
2562 //TODO: work out platform independent constraints and factor those out
2563 // of the per target tables
2564 // handle multiple constraint codes
2565 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
2567 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
2569 const char** table = 0;
2571 //Grab the translation table from TargetAsmInfo if it exists
2574 const TargetMachineRegistry::Entry* Match =
2575 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
2577 //Per platform Target Machines don't exist, so create it
2578 // this must be done only once
2579 const TargetMachine* TM = Match->CtorFn(*TheModule, "");
2580 TAsm = TM->getTargetAsmInfo();
2584 table = TAsm->getAsmCBE();
2586 //Search the translation table if it exists
2587 for (int i = 0; table && table[i]; i += 2)
2588 if (c.Codes[0] == table[i])
2591 //default is identity
2595 //TODO: import logic from AsmPrinter.cpp
2596 static std::string gccifyAsm(std::string asmstr) {
2597 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
2598 if (asmstr[i] == '\n')
2599 asmstr.replace(i, 1, "\\n");
2600 else if (asmstr[i] == '\t')
2601 asmstr.replace(i, 1, "\\t");
2602 else if (asmstr[i] == '$') {
2603 if (asmstr[i + 1] == '{') {
2604 std::string::size_type a = asmstr.find_first_of(':', i + 1);
2605 std::string::size_type b = asmstr.find_first_of('}', i + 1);
2606 std::string n = "%" +
2607 asmstr.substr(a + 1, b - a - 1) +
2608 asmstr.substr(i + 2, a - i - 2);
2609 asmstr.replace(i, b - i + 1, n);
2612 asmstr.replace(i, 1, "%");
2614 else if (asmstr[i] == '%')//grr
2615 { asmstr.replace(i, 1, "%%"); ++i;}
2620 //TODO: assumptions about what consume arguments from the call are likely wrong
2621 // handle communitivity
2622 void CWriter::visitInlineAsm(CallInst &CI) {
2623 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
2624 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
2625 std::vector<std::pair<std::string, Value*> > Input;
2626 std::vector<std::pair<std::string, Value*> > Output;
2627 std::string Clobber;
2628 int count = CI.getType() == Type::VoidTy ? 1 : 0;
2629 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
2630 E = Constraints.end(); I != E; ++I) {
2631 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
2633 InterpretASMConstraint(*I);
2636 assert(0 && "Unknown asm constraint");
2638 case InlineAsm::isInput: {
2640 Input.push_back(std::make_pair(c, count ? CI.getOperand(count) : &CI));
2641 ++count; //consume arg
2645 case InlineAsm::isOutput: {
2647 Output.push_back(std::make_pair("="+((I->isEarlyClobber ? "&" : "")+c),
2648 count ? CI.getOperand(count) : &CI));
2649 ++count; //consume arg
2653 case InlineAsm::isClobber: {
2655 Clobber += ",\"" + c + "\"";
2661 //fix up the asm string for gcc
2662 std::string asmstr = gccifyAsm(as->getAsmString());
2664 Out << "__asm__ volatile (\"" << asmstr << "\"\n";
2666 for (std::vector<std::pair<std::string, Value*> >::iterator I = Output.begin(),
2667 E = Output.end(); I != E; ++I) {
2668 Out << "\"" << I->first << "\"(";
2669 writeOperandRaw(I->second);
2675 for (std::vector<std::pair<std::string, Value*> >::iterator I = Input.begin(),
2676 E = Input.end(); I != E; ++I) {
2677 Out << "\"" << I->first << "\"(";
2678 writeOperandRaw(I->second);
2684 Out << "\n :" << Clobber.substr(1);
2688 void CWriter::visitMallocInst(MallocInst &I) {
2689 assert(0 && "lowerallocations pass didn't work!");
2692 void CWriter::visitAllocaInst(AllocaInst &I) {
2694 printType(Out, I.getType());
2695 Out << ") alloca(sizeof(";
2696 printType(Out, I.getType()->getElementType());
2698 if (I.isArrayAllocation()) {
2700 writeOperand(I.getOperand(0));
2705 void CWriter::visitFreeInst(FreeInst &I) {
2706 assert(0 && "lowerallocations pass didn't work!");
2709 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2710 gep_type_iterator E) {
2711 bool HasImplicitAddress = false;
2712 // If accessing a global value with no indexing, avoid *(&GV) syndrome
2713 if (isa<GlobalValue>(Ptr)) {
2714 HasImplicitAddress = true;
2715 } else if (isDirectAlloca(Ptr)) {
2716 HasImplicitAddress = true;
2720 if (!HasImplicitAddress)
2721 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
2723 writeOperandInternal(Ptr);
2727 const Constant *CI = dyn_cast<Constant>(I.getOperand());
2728 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2731 writeOperandInternal(Ptr);
2733 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
2735 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
2738 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
2739 "Can only have implicit address with direct accessing");
2741 if (HasImplicitAddress) {
2743 } else if (CI && CI->isNullValue()) {
2744 gep_type_iterator TmpI = I; ++TmpI;
2746 // Print out the -> operator if possible...
2747 if (TmpI != E && isa<StructType>(*TmpI)) {
2748 Out << (HasImplicitAddress ? "." : "->");
2749 Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
2755 if (isa<StructType>(*I)) {
2756 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
2759 writeOperand(I.getOperand());
2764 void CWriter::visitLoadInst(LoadInst &I) {
2766 if (I.isVolatile()) {
2768 printType(Out, I.getType(), false, "volatile*");
2772 writeOperand(I.getOperand(0));
2778 void CWriter::visitStoreInst(StoreInst &I) {
2780 if (I.isVolatile()) {
2782 printType(Out, I.getOperand(0)->getType(), false, " volatile*");
2785 writeOperand(I.getPointerOperand());
2786 if (I.isVolatile()) Out << ')';
2788 writeOperand(I.getOperand(0));
2791 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
2793 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2797 void CWriter::visitVAArgInst(VAArgInst &I) {
2798 Out << "va_arg(*(va_list*)";
2799 writeOperand(I.getOperand(0));
2801 printType(Out, I.getType());
2805 //===----------------------------------------------------------------------===//
2806 // External Interface declaration
2807 //===----------------------------------------------------------------------===//
2809 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2811 CodeGenFileType FileType,
2813 if (FileType != TargetMachine::AssemblyFile) return true;
2815 PM.add(createLowerGCPass());
2816 PM.add(createLowerAllocationsPass(true));
2817 PM.add(createLowerInvokePass());
2818 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
2819 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
2820 PM.add(new CWriter(o));