1 //===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/ParamAttrsList.h"
22 #include "llvm/Pass.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/InlineAsm.h"
28 #include "llvm/Analysis/ConstantsScanner.h"
29 #include "llvm/Analysis/FindUsedTypes.h"
30 #include "llvm/Analysis/LoopInfo.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/CodeGen/IntrinsicLowering.h"
33 #include "llvm/Transforms/Scalar.h"
34 #include "llvm/Target/TargetMachineRegistry.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Support/CallSite.h"
38 #include "llvm/Support/CFG.h"
39 #include "llvm/Support/GetElementPtrTypeIterator.h"
40 #include "llvm/Support/InstVisitor.h"
41 #include "llvm/Support/Mangler.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Config/config.h"
52 // Register the target.
53 RegisterTarget<CTargetMachine> X("c", " C backend");
55 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
56 /// any unnamed structure types that are used by the program, and merges
57 /// external functions with the same name.
59 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
62 CBackendNameAllUsedStructsAndMergeFunctions()
63 : ModulePass((intptr_t)&ID) {}
64 void getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.addRequired<FindUsedTypes>();
68 virtual const char *getPassName() const {
69 return "C backend type canonicalizer";
72 virtual bool runOnModule(Module &M);
75 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
77 /// CWriter - This class is the main chunk of code that converts an LLVM
78 /// module to a C translation unit.
79 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
81 IntrinsicLowering *IL;
84 const Module *TheModule;
85 const TargetAsmInfo* TAsm;
87 std::map<const Type *, std::string> TypeNames;
88 std::map<const ConstantFP *, unsigned> FPConstantMap;
89 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
90 std::set<const Value*> ByValParams;
94 CWriter(std::ostream &o)
95 : FunctionPass((intptr_t)&ID), Out(o), IL(0), Mang(0), LI(0),
96 TheModule(0), TAsm(0), TD(0) {}
98 virtual const char *getPassName() const { return "C backend"; }
100 void getAnalysisUsage(AnalysisUsage &AU) const {
101 AU.addRequired<LoopInfo>();
102 AU.setPreservesAll();
105 virtual bool doInitialization(Module &M);
107 bool runOnFunction(Function &F) {
108 LI = &getAnalysis<LoopInfo>();
110 // Get rid of intrinsics we can't handle.
113 // Output all floating point constants that cannot be printed accurately.
114 printFloatingPointConstants(F);
120 virtual bool doFinalization(Module &M) {
123 FPConstantMap.clear();
125 intrinsicPrototypesAlreadyGenerated.clear();
130 std::ostream &printType(std::ostream &Out, const Type *Ty,
131 bool isSigned = false,
132 const std::string &VariableName = "",
133 bool IgnoreName = false,
134 const ParamAttrsList *PAL = 0);
135 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
137 const std::string &NameSoFar = "");
139 void printStructReturnPointerFunctionType(std::ostream &Out,
140 const ParamAttrsList *PAL,
141 const PointerType *Ty);
143 void writeOperand(Value *Operand);
144 void writeOperandRaw(Value *Operand);
145 void writeOperandInternal(Value *Operand);
146 void writeOperandWithCast(Value* Operand, unsigned Opcode);
147 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
148 bool writeInstructionCast(const Instruction &I);
150 void writeMemoryAccess(Value *Operand, const Type *OperandType,
151 bool IsVolatile, unsigned Alignment);
154 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
156 void lowerIntrinsics(Function &F);
158 void printModule(Module *M);
159 void printModuleTypes(const TypeSymbolTable &ST);
160 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
161 void printFloatingPointConstants(Function &F);
162 void printFunctionSignature(const Function *F, bool Prototype);
164 void printFunction(Function &);
165 void printBasicBlock(BasicBlock *BB);
166 void printLoop(Loop *L);
168 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
169 void printConstant(Constant *CPV);
170 void printConstantWithCast(Constant *CPV, unsigned Opcode);
171 bool printConstExprCast(const ConstantExpr *CE);
172 void printConstantArray(ConstantArray *CPA);
173 void printConstantVector(ConstantVector *CP);
175 // isInlinableInst - Attempt to inline instructions into their uses to build
176 // trees as much as possible. To do this, we have to consistently decide
177 // what is acceptable to inline, so that variable declarations don't get
178 // printed and an extra copy of the expr is not emitted.
180 static bool isInlinableInst(const Instruction &I) {
181 // Always inline cmp instructions, even if they are shared by multiple
182 // expressions. GCC generates horrible code if we don't.
186 // Must be an expression, must be used exactly once. If it is dead, we
187 // emit it inline where it would go.
188 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
189 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
190 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I))
191 // Don't inline a load across a store or other bad things!
194 // Must not be used in inline asm or extractelement.
196 (isInlineAsm(*I.use_back()) || isa<ExtractElementInst>(I)))
199 // Only inline instruction it if it's use is in the same BB as the inst.
200 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
203 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
204 // variables which are accessed with the & operator. This causes GCC to
205 // generate significantly better code than to emit alloca calls directly.
207 static const AllocaInst *isDirectAlloca(const Value *V) {
208 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
209 if (!AI) return false;
210 if (AI->isArrayAllocation())
211 return 0; // FIXME: we can also inline fixed size array allocas!
212 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
217 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
218 static bool isInlineAsm(const Instruction& I) {
219 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
224 // Instruction visitation functions
225 friend class InstVisitor<CWriter>;
227 void visitReturnInst(ReturnInst &I);
228 void visitBranchInst(BranchInst &I);
229 void visitSwitchInst(SwitchInst &I);
230 void visitInvokeInst(InvokeInst &I) {
231 assert(0 && "Lowerinvoke pass didn't work!");
234 void visitUnwindInst(UnwindInst &I) {
235 assert(0 && "Lowerinvoke pass didn't work!");
237 void visitUnreachableInst(UnreachableInst &I);
239 void visitPHINode(PHINode &I);
240 void visitBinaryOperator(Instruction &I);
241 void visitICmpInst(ICmpInst &I);
242 void visitFCmpInst(FCmpInst &I);
244 void visitCastInst (CastInst &I);
245 void visitSelectInst(SelectInst &I);
246 void visitCallInst (CallInst &I);
247 void visitInlineAsm(CallInst &I);
249 void visitMallocInst(MallocInst &I);
250 void visitAllocaInst(AllocaInst &I);
251 void visitFreeInst (FreeInst &I);
252 void visitLoadInst (LoadInst &I);
253 void visitStoreInst (StoreInst &I);
254 void visitGetElementPtrInst(GetElementPtrInst &I);
255 void visitVAArgInst (VAArgInst &I);
257 void visitInsertElementInst(InsertElementInst &I);
258 void visitExtractElementInst(ExtractElementInst &I);
260 void visitInstruction(Instruction &I) {
261 cerr << "C Writer does not know about " << I;
265 void outputLValue(Instruction *I) {
266 Out << " " << GetValueName(I) << " = ";
269 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
270 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
271 BasicBlock *Successor, unsigned Indent);
272 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
274 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
275 gep_type_iterator E);
277 std::string GetValueName(const Value *Operand);
281 char CWriter::ID = 0;
283 /// This method inserts names for any unnamed structure types that are used by
284 /// the program, and removes names from structure types that are not used by the
287 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
288 // Get a set of types that are used by the program...
289 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
291 // Loop over the module symbol table, removing types from UT that are
292 // already named, and removing names for types that are not used.
294 TypeSymbolTable &TST = M.getTypeSymbolTable();
295 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
297 TypeSymbolTable::iterator I = TI++;
299 // If this isn't a struct type, remove it from our set of types to name.
300 // This simplifies emission later.
301 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second)) {
304 // If this is not used, remove it from the symbol table.
305 std::set<const Type *>::iterator UTI = UT.find(I->second);
309 UT.erase(UTI); // Only keep one name for this type.
313 // UT now contains types that are not named. Loop over it, naming
316 bool Changed = false;
317 unsigned RenameCounter = 0;
318 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
320 if (const StructType *ST = dyn_cast<StructType>(*I)) {
321 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
327 // Loop over all external functions and globals. If we have two with
328 // identical names, merge them.
329 // FIXME: This code should disappear when we don't allow values with the same
330 // names when they have different types!
331 std::map<std::string, GlobalValue*> ExtSymbols;
332 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
334 if (GV->isDeclaration() && GV->hasName()) {
335 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
336 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
338 // Found a conflict, replace this global with the previous one.
339 GlobalValue *OldGV = X.first->second;
340 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
341 GV->eraseFromParent();
346 // Do the same for globals.
347 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
349 GlobalVariable *GV = I++;
350 if (GV->isDeclaration() && GV->hasName()) {
351 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
352 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
354 // Found a conflict, replace this global with the previous one.
355 GlobalValue *OldGV = X.first->second;
356 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
357 GV->eraseFromParent();
366 /// printStructReturnPointerFunctionType - This is like printType for a struct
367 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
368 /// print it as "Struct (*)(...)", for struct return functions.
369 void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
370 const ParamAttrsList *PAL,
371 const PointerType *TheTy) {
372 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
373 std::stringstream FunctionInnards;
374 FunctionInnards << " (*) (";
375 bool PrintedType = false;
377 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
378 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
380 for (++I, ++Idx; I != E; ++I, ++Idx) {
382 FunctionInnards << ", ";
383 const Type *ArgTy = *I;
384 if (PAL && PAL->paramHasAttr(Idx, ParamAttr::ByVal)) {
385 assert(isa<PointerType>(ArgTy));
386 ArgTy = cast<PointerType>(ArgTy)->getElementType();
388 printType(FunctionInnards, ArgTy,
389 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt), "");
392 if (FTy->isVarArg()) {
394 FunctionInnards << ", ...";
395 } else if (!PrintedType) {
396 FunctionInnards << "void";
398 FunctionInnards << ')';
399 std::string tstr = FunctionInnards.str();
400 printType(Out, RetTy,
401 /*isSigned=*/PAL && PAL->paramHasAttr(0, ParamAttr::SExt), tstr);
405 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
406 const std::string &NameSoFar) {
407 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
408 "Invalid type for printSimpleType");
409 switch (Ty->getTypeID()) {
410 case Type::VoidTyID: return Out << "void " << NameSoFar;
411 case Type::IntegerTyID: {
412 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
414 return Out << "bool " << NameSoFar;
415 else if (NumBits <= 8)
416 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
417 else if (NumBits <= 16)
418 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
419 else if (NumBits <= 32)
420 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
422 assert(NumBits <= 64 && "Bit widths > 64 not implemented yet");
423 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
426 case Type::FloatTyID: return Out << "float " << NameSoFar;
427 case Type::DoubleTyID: return Out << "double " << NameSoFar;
428 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
429 // present matches host 'long double'.
430 case Type::X86_FP80TyID:
431 case Type::PPC_FP128TyID:
432 case Type::FP128TyID: return Out << "long double " << NameSoFar;
434 case Type::VectorTyID: {
435 const VectorType *VTy = cast<VectorType>(Ty);
436 return printSimpleType(Out, VTy->getElementType(), isSigned,
437 " __attribute__((vector_size(" +
438 utostr(TD->getABITypeSize(VTy)) + " ))) " + NameSoFar);
442 cerr << "Unknown primitive type: " << *Ty << "\n";
447 // Pass the Type* and the variable name and this prints out the variable
450 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
451 bool isSigned, const std::string &NameSoFar,
452 bool IgnoreName, const ParamAttrsList* PAL) {
453 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
454 printSimpleType(Out, Ty, isSigned, NameSoFar);
458 // Check to see if the type is named.
459 if (!IgnoreName || isa<OpaqueType>(Ty)) {
460 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
461 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
464 switch (Ty->getTypeID()) {
465 case Type::FunctionTyID: {
466 const FunctionType *FTy = cast<FunctionType>(Ty);
467 std::stringstream FunctionInnards;
468 FunctionInnards << " (" << NameSoFar << ") (";
470 for (FunctionType::param_iterator I = FTy->param_begin(),
471 E = FTy->param_end(); I != E; ++I) {
472 const Type *ArgTy = *I;
473 if (PAL && PAL->paramHasAttr(Idx, ParamAttr::ByVal)) {
474 assert(isa<PointerType>(ArgTy));
475 ArgTy = cast<PointerType>(ArgTy)->getElementType();
477 if (I != FTy->param_begin())
478 FunctionInnards << ", ";
479 printType(FunctionInnards, ArgTy,
480 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt), "");
483 if (FTy->isVarArg()) {
484 if (FTy->getNumParams())
485 FunctionInnards << ", ...";
486 } else if (!FTy->getNumParams()) {
487 FunctionInnards << "void";
489 FunctionInnards << ')';
490 std::string tstr = FunctionInnards.str();
491 printType(Out, FTy->getReturnType(),
492 /*isSigned=*/PAL && PAL->paramHasAttr(0, ParamAttr::SExt), tstr);
495 case Type::StructTyID: {
496 const StructType *STy = cast<StructType>(Ty);
497 Out << NameSoFar + " {\n";
499 for (StructType::element_iterator I = STy->element_begin(),
500 E = STy->element_end(); I != E; ++I) {
502 printType(Out, *I, false, "field" + utostr(Idx++));
507 Out << " __attribute__ ((packed))";
511 case Type::PointerTyID: {
512 const PointerType *PTy = cast<PointerType>(Ty);
513 std::string ptrName = "*" + NameSoFar;
515 if (isa<ArrayType>(PTy->getElementType()) ||
516 isa<VectorType>(PTy->getElementType()))
517 ptrName = "(" + ptrName + ")";
520 // Must be a function ptr cast!
521 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
522 return printType(Out, PTy->getElementType(), false, ptrName);
525 case Type::ArrayTyID: {
526 const ArrayType *ATy = cast<ArrayType>(Ty);
527 unsigned NumElements = ATy->getNumElements();
528 if (NumElements == 0) NumElements = 1;
529 return printType(Out, ATy->getElementType(), false,
530 NameSoFar + "[" + utostr(NumElements) + "]");
533 case Type::OpaqueTyID: {
534 static int Count = 0;
535 std::string TyName = "struct opaque_" + itostr(Count++);
536 assert(TypeNames.find(Ty) == TypeNames.end());
537 TypeNames[Ty] = TyName;
538 return Out << TyName << ' ' << NameSoFar;
541 assert(0 && "Unhandled case in getTypeProps!");
548 void CWriter::printConstantArray(ConstantArray *CPA) {
550 // As a special case, print the array as a string if it is an array of
551 // ubytes or an array of sbytes with positive values.
553 const Type *ETy = CPA->getType()->getElementType();
554 bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
556 // Make sure the last character is a null char, as automatically added by C
557 if (isString && (CPA->getNumOperands() == 0 ||
558 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
563 // Keep track of whether the last number was a hexadecimal escape
564 bool LastWasHex = false;
566 // Do not include the last character, which we know is null
567 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
568 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
570 // Print it out literally if it is a printable character. The only thing
571 // to be careful about is when the last letter output was a hex escape
572 // code, in which case we have to be careful not to print out hex digits
573 // explicitly (the C compiler thinks it is a continuation of the previous
574 // character, sheesh...)
576 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
578 if (C == '"' || C == '\\')
585 case '\n': Out << "\\n"; break;
586 case '\t': Out << "\\t"; break;
587 case '\r': Out << "\\r"; break;
588 case '\v': Out << "\\v"; break;
589 case '\a': Out << "\\a"; break;
590 case '\"': Out << "\\\""; break;
591 case '\'': Out << "\\\'"; break;
594 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
595 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
604 if (CPA->getNumOperands()) {
606 printConstant(cast<Constant>(CPA->getOperand(0)));
607 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
609 printConstant(cast<Constant>(CPA->getOperand(i)));
616 void CWriter::printConstantVector(ConstantVector *CP) {
618 if (CP->getNumOperands()) {
620 printConstant(cast<Constant>(CP->getOperand(0)));
621 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
623 printConstant(cast<Constant>(CP->getOperand(i)));
629 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
630 // textually as a double (rather than as a reference to a stack-allocated
631 // variable). We decide this by converting CFP to a string and back into a
632 // double, and then checking whether the conversion results in a bit-equal
633 // double to the original value of CFP. This depends on us and the target C
634 // compiler agreeing on the conversion process (which is pretty likely since we
635 // only deal in IEEE FP).
637 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
638 // Do long doubles in hex for now.
639 if (CFP->getType()!=Type::FloatTy && CFP->getType()!=Type::DoubleTy)
641 APFloat APF = APFloat(CFP->getValueAPF()); // copy
642 if (CFP->getType()==Type::FloatTy)
643 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
644 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
646 sprintf(Buffer, "%a", APF.convertToDouble());
647 if (!strncmp(Buffer, "0x", 2) ||
648 !strncmp(Buffer, "-0x", 3) ||
649 !strncmp(Buffer, "+0x", 3))
650 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
653 std::string StrVal = ftostr(APF);
655 while (StrVal[0] == ' ')
656 StrVal.erase(StrVal.begin());
658 // Check to make sure that the stringized number is not some string like "Inf"
659 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
660 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
661 ((StrVal[0] == '-' || StrVal[0] == '+') &&
662 (StrVal[1] >= '0' && StrVal[1] <= '9')))
663 // Reparse stringized version!
664 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
669 /// Print out the casting for a cast operation. This does the double casting
670 /// necessary for conversion to the destination type, if necessary.
671 /// @brief Print a cast
672 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
673 // Print the destination type cast
675 case Instruction::UIToFP:
676 case Instruction::SIToFP:
677 case Instruction::IntToPtr:
678 case Instruction::Trunc:
679 case Instruction::BitCast:
680 case Instruction::FPExt:
681 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
683 printType(Out, DstTy);
686 case Instruction::ZExt:
687 case Instruction::PtrToInt:
688 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
690 printSimpleType(Out, DstTy, false);
693 case Instruction::SExt:
694 case Instruction::FPToSI: // For these, make sure we get a signed dest
696 printSimpleType(Out, DstTy, true);
700 assert(0 && "Invalid cast opcode");
703 // Print the source type cast
705 case Instruction::UIToFP:
706 case Instruction::ZExt:
708 printSimpleType(Out, SrcTy, false);
711 case Instruction::SIToFP:
712 case Instruction::SExt:
714 printSimpleType(Out, SrcTy, true);
717 case Instruction::IntToPtr:
718 case Instruction::PtrToInt:
719 // Avoid "cast to pointer from integer of different size" warnings
720 Out << "(unsigned long)";
722 case Instruction::Trunc:
723 case Instruction::BitCast:
724 case Instruction::FPExt:
725 case Instruction::FPTrunc:
726 case Instruction::FPToSI:
727 case Instruction::FPToUI:
728 break; // These don't need a source cast.
730 assert(0 && "Invalid cast opcode");
735 // printConstant - The LLVM Constant to C Constant converter.
736 void CWriter::printConstant(Constant *CPV) {
737 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
738 switch (CE->getOpcode()) {
739 case Instruction::Trunc:
740 case Instruction::ZExt:
741 case Instruction::SExt:
742 case Instruction::FPTrunc:
743 case Instruction::FPExt:
744 case Instruction::UIToFP:
745 case Instruction::SIToFP:
746 case Instruction::FPToUI:
747 case Instruction::FPToSI:
748 case Instruction::PtrToInt:
749 case Instruction::IntToPtr:
750 case Instruction::BitCast:
752 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
753 if (CE->getOpcode() == Instruction::SExt &&
754 CE->getOperand(0)->getType() == Type::Int1Ty) {
755 // Make sure we really sext from bool here by subtracting from 0
758 printConstant(CE->getOperand(0));
759 if (CE->getType() == Type::Int1Ty &&
760 (CE->getOpcode() == Instruction::Trunc ||
761 CE->getOpcode() == Instruction::FPToUI ||
762 CE->getOpcode() == Instruction::FPToSI ||
763 CE->getOpcode() == Instruction::PtrToInt)) {
764 // Make sure we really truncate to bool here by anding with 1
770 case Instruction::GetElementPtr:
772 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
776 case Instruction::Select:
778 printConstant(CE->getOperand(0));
780 printConstant(CE->getOperand(1));
782 printConstant(CE->getOperand(2));
785 case Instruction::Add:
786 case Instruction::Sub:
787 case Instruction::Mul:
788 case Instruction::SDiv:
789 case Instruction::UDiv:
790 case Instruction::FDiv:
791 case Instruction::URem:
792 case Instruction::SRem:
793 case Instruction::FRem:
794 case Instruction::And:
795 case Instruction::Or:
796 case Instruction::Xor:
797 case Instruction::ICmp:
798 case Instruction::Shl:
799 case Instruction::LShr:
800 case Instruction::AShr:
803 bool NeedsClosingParens = printConstExprCast(CE);
804 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
805 switch (CE->getOpcode()) {
806 case Instruction::Add: Out << " + "; break;
807 case Instruction::Sub: Out << " - "; break;
808 case Instruction::Mul: Out << " * "; break;
809 case Instruction::URem:
810 case Instruction::SRem:
811 case Instruction::FRem: Out << " % "; break;
812 case Instruction::UDiv:
813 case Instruction::SDiv:
814 case Instruction::FDiv: Out << " / "; break;
815 case Instruction::And: Out << " & "; break;
816 case Instruction::Or: Out << " | "; break;
817 case Instruction::Xor: Out << " ^ "; break;
818 case Instruction::Shl: Out << " << "; break;
819 case Instruction::LShr:
820 case Instruction::AShr: Out << " >> "; break;
821 case Instruction::ICmp:
822 switch (CE->getPredicate()) {
823 case ICmpInst::ICMP_EQ: Out << " == "; break;
824 case ICmpInst::ICMP_NE: Out << " != "; break;
825 case ICmpInst::ICMP_SLT:
826 case ICmpInst::ICMP_ULT: Out << " < "; break;
827 case ICmpInst::ICMP_SLE:
828 case ICmpInst::ICMP_ULE: Out << " <= "; break;
829 case ICmpInst::ICMP_SGT:
830 case ICmpInst::ICMP_UGT: Out << " > "; break;
831 case ICmpInst::ICMP_SGE:
832 case ICmpInst::ICMP_UGE: Out << " >= "; break;
833 default: assert(0 && "Illegal ICmp predicate");
836 default: assert(0 && "Illegal opcode here!");
838 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
839 if (NeedsClosingParens)
844 case Instruction::FCmp: {
846 bool NeedsClosingParens = printConstExprCast(CE);
847 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
849 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
853 switch (CE->getPredicate()) {
854 default: assert(0 && "Illegal FCmp predicate");
855 case FCmpInst::FCMP_ORD: op = "ord"; break;
856 case FCmpInst::FCMP_UNO: op = "uno"; break;
857 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
858 case FCmpInst::FCMP_UNE: op = "une"; break;
859 case FCmpInst::FCMP_ULT: op = "ult"; break;
860 case FCmpInst::FCMP_ULE: op = "ule"; break;
861 case FCmpInst::FCMP_UGT: op = "ugt"; break;
862 case FCmpInst::FCMP_UGE: op = "uge"; break;
863 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
864 case FCmpInst::FCMP_ONE: op = "one"; break;
865 case FCmpInst::FCMP_OLT: op = "olt"; break;
866 case FCmpInst::FCMP_OLE: op = "ole"; break;
867 case FCmpInst::FCMP_OGT: op = "ogt"; break;
868 case FCmpInst::FCMP_OGE: op = "oge"; break;
870 Out << "llvm_fcmp_" << op << "(";
871 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
873 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
876 if (NeedsClosingParens)
882 cerr << "CWriter Error: Unhandled constant expression: "
886 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
888 printType(Out, CPV->getType()); // sign doesn't matter
889 Out << ")/*UNDEF*/0)";
893 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
894 const Type* Ty = CI->getType();
895 if (Ty == Type::Int1Ty)
896 Out << (CI->getZExtValue() ? '1' : '0');
897 else if (Ty == Type::Int32Ty)
898 Out << CI->getZExtValue() << 'u';
899 else if (Ty->getPrimitiveSizeInBits() > 32)
900 Out << CI->getZExtValue() << "ull";
903 printSimpleType(Out, Ty, false) << ')';
904 if (CI->isMinValue(true))
905 Out << CI->getZExtValue() << 'u';
907 Out << CI->getSExtValue();
913 switch (CPV->getType()->getTypeID()) {
914 case Type::FloatTyID:
915 case Type::DoubleTyID:
916 case Type::X86_FP80TyID:
917 case Type::PPC_FP128TyID:
918 case Type::FP128TyID: {
919 ConstantFP *FPC = cast<ConstantFP>(CPV);
920 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
921 if (I != FPConstantMap.end()) {
922 // Because of FP precision problems we must load from a stack allocated
923 // value that holds the value in hex.
924 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" :
925 FPC->getType() == Type::DoubleTy ? "double" :
927 << "*)&FPConstant" << I->second << ')';
929 assert(FPC->getType() == Type::FloatTy ||
930 FPC->getType() == Type::DoubleTy);
931 double V = FPC->getType() == Type::FloatTy ?
932 FPC->getValueAPF().convertToFloat() :
933 FPC->getValueAPF().convertToDouble();
937 // FIXME the actual NaN bits should be emitted.
938 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
940 const unsigned long QuietNaN = 0x7ff8UL;
941 //const unsigned long SignalNaN = 0x7ff4UL;
943 // We need to grab the first part of the FP #
946 uint64_t ll = DoubleToBits(V);
947 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
949 std::string Num(&Buffer[0], &Buffer[6]);
950 unsigned long Val = strtoul(Num.c_str(), 0, 16);
952 if (FPC->getType() == Type::FloatTy)
953 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
954 << Buffer << "\") /*nan*/ ";
956 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
957 << Buffer << "\") /*nan*/ ";
958 } else if (IsInf(V)) {
960 if (V < 0) Out << '-';
961 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
965 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
966 // Print out the constant as a floating point number.
968 sprintf(Buffer, "%a", V);
971 Num = ftostr(FPC->getValueAPF());
979 case Type::ArrayTyID:
980 if (ConstantArray *CA = cast<ConstantArray>(CPV)) {
981 printConstantArray(CA);
983 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
984 const ArrayType *AT = cast<ArrayType>(CPV->getType());
986 if (AT->getNumElements()) {
988 Constant *CZ = Constant::getNullValue(AT->getElementType());
990 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
999 case Type::VectorTyID:
1000 // Use C99 compound expression literal initializer syntax.
1002 printType(Out, CPV->getType());
1004 if (ConstantVector *CV = cast<ConstantVector>(CPV)) {
1005 printConstantVector(CV);
1007 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1008 const VectorType *VT = cast<VectorType>(CPV->getType());
1010 Constant *CZ = Constant::getNullValue(VT->getElementType());
1012 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1020 case Type::StructTyID:
1021 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1022 const StructType *ST = cast<StructType>(CPV->getType());
1024 if (ST->getNumElements()) {
1026 printConstant(Constant::getNullValue(ST->getElementType(0)));
1027 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1029 printConstant(Constant::getNullValue(ST->getElementType(i)));
1035 if (CPV->getNumOperands()) {
1037 printConstant(cast<Constant>(CPV->getOperand(0)));
1038 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1040 printConstant(cast<Constant>(CPV->getOperand(i)));
1047 case Type::PointerTyID:
1048 if (isa<ConstantPointerNull>(CPV)) {
1050 printType(Out, CPV->getType()); // sign doesn't matter
1051 Out << ")/*NULL*/0)";
1053 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1059 cerr << "Unknown constant type: " << *CPV << "\n";
1064 // Some constant expressions need to be casted back to the original types
1065 // because their operands were casted to the expected type. This function takes
1066 // care of detecting that case and printing the cast for the ConstantExpr.
1067 bool CWriter::printConstExprCast(const ConstantExpr* CE) {
1068 bool NeedsExplicitCast = false;
1069 const Type *Ty = CE->getOperand(0)->getType();
1070 bool TypeIsSigned = false;
1071 switch (CE->getOpcode()) {
1072 case Instruction::LShr:
1073 case Instruction::URem:
1074 case Instruction::UDiv: NeedsExplicitCast = true; break;
1075 case Instruction::AShr:
1076 case Instruction::SRem:
1077 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1078 case Instruction::SExt:
1080 NeedsExplicitCast = true;
1081 TypeIsSigned = true;
1083 case Instruction::ZExt:
1084 case Instruction::Trunc:
1085 case Instruction::FPTrunc:
1086 case Instruction::FPExt:
1087 case Instruction::UIToFP:
1088 case Instruction::SIToFP:
1089 case Instruction::FPToUI:
1090 case Instruction::FPToSI:
1091 case Instruction::PtrToInt:
1092 case Instruction::IntToPtr:
1093 case Instruction::BitCast:
1095 NeedsExplicitCast = true;
1099 if (NeedsExplicitCast) {
1101 if (Ty->isInteger() && Ty != Type::Int1Ty)
1102 printSimpleType(Out, Ty, TypeIsSigned);
1104 printType(Out, Ty); // not integer, sign doesn't matter
1107 return NeedsExplicitCast;
1110 // Print a constant assuming that it is the operand for a given Opcode. The
1111 // opcodes that care about sign need to cast their operands to the expected
1112 // type before the operation proceeds. This function does the casting.
1113 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1115 // Extract the operand's type, we'll need it.
1116 const Type* OpTy = CPV->getType();
1118 // Indicate whether to do the cast or not.
1119 bool shouldCast = false;
1120 bool typeIsSigned = false;
1122 // Based on the Opcode for which this Constant is being written, determine
1123 // the new type to which the operand should be casted by setting the value
1124 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1128 // for most instructions, it doesn't matter
1130 case Instruction::LShr:
1131 case Instruction::UDiv:
1132 case Instruction::URem:
1135 case Instruction::AShr:
1136 case Instruction::SDiv:
1137 case Instruction::SRem:
1139 typeIsSigned = true;
1143 // Write out the casted constant if we should, otherwise just write the
1147 printSimpleType(Out, OpTy, typeIsSigned);
1155 std::string CWriter::GetValueName(const Value *Operand) {
1158 if (!isa<GlobalValue>(Operand) && Operand->getName() != "") {
1159 std::string VarName;
1161 Name = Operand->getName();
1162 VarName.reserve(Name.capacity());
1164 for (std::string::iterator I = Name.begin(), E = Name.end();
1168 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1169 (ch >= '0' && ch <= '9') || ch == '_')) {
1171 sprintf(buffer, "_%x_", ch);
1177 Name = "llvm_cbe_" + VarName;
1179 Name = Mang->getValueName(Operand);
1185 void CWriter::writeOperandInternal(Value *Operand) {
1186 if (Instruction *I = dyn_cast<Instruction>(Operand))
1187 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1188 // Should we inline this instruction to build a tree?
1195 Constant* CPV = dyn_cast<Constant>(Operand);
1197 if (CPV && !isa<GlobalValue>(CPV))
1200 Out << GetValueName(Operand);
1203 void CWriter::writeOperandRaw(Value *Operand) {
1204 Constant* CPV = dyn_cast<Constant>(Operand);
1205 if (CPV && !isa<GlobalValue>(CPV)) {
1208 Out << GetValueName(Operand);
1212 void CWriter::writeOperand(Value *Operand) {
1213 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1214 Out << "(&"; // Global variables are referenced as their addresses by llvm
1216 writeOperandInternal(Operand);
1218 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1222 // Some instructions need to have their result value casted back to the
1223 // original types because their operands were casted to the expected type.
1224 // This function takes care of detecting that case and printing the cast
1225 // for the Instruction.
1226 bool CWriter::writeInstructionCast(const Instruction &I) {
1227 const Type *Ty = I.getOperand(0)->getType();
1228 switch (I.getOpcode()) {
1229 case Instruction::LShr:
1230 case Instruction::URem:
1231 case Instruction::UDiv:
1233 printSimpleType(Out, Ty, false);
1236 case Instruction::AShr:
1237 case Instruction::SRem:
1238 case Instruction::SDiv:
1240 printSimpleType(Out, Ty, true);
1248 // Write the operand with a cast to another type based on the Opcode being used.
1249 // This will be used in cases where an instruction has specific type
1250 // requirements (usually signedness) for its operands.
1251 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1253 // Extract the operand's type, we'll need it.
1254 const Type* OpTy = Operand->getType();
1256 // Indicate whether to do the cast or not.
1257 bool shouldCast = false;
1259 // Indicate whether the cast should be to a signed type or not.
1260 bool castIsSigned = false;
1262 // Based on the Opcode for which this Operand is being written, determine
1263 // the new type to which the operand should be casted by setting the value
1264 // of OpTy. If we change OpTy, also set shouldCast to true.
1267 // for most instructions, it doesn't matter
1269 case Instruction::LShr:
1270 case Instruction::UDiv:
1271 case Instruction::URem: // Cast to unsigned first
1273 castIsSigned = false;
1275 case Instruction::GetElementPtr:
1276 case Instruction::AShr:
1277 case Instruction::SDiv:
1278 case Instruction::SRem: // Cast to signed first
1280 castIsSigned = true;
1284 // Write out the casted operand if we should, otherwise just write the
1288 printSimpleType(Out, OpTy, castIsSigned);
1290 writeOperand(Operand);
1293 writeOperand(Operand);
1296 // Write the operand with a cast to another type based on the icmp predicate
1298 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1299 // This has to do a cast to ensure the operand has the right signedness.
1300 // Also, if the operand is a pointer, we make sure to cast to an integer when
1301 // doing the comparison both for signedness and so that the C compiler doesn't
1302 // optimize things like "p < NULL" to false (p may contain an integer value
1304 bool shouldCast = Cmp.isRelational();
1306 // Write out the casted operand if we should, otherwise just write the
1309 writeOperand(Operand);
1313 // Should this be a signed comparison? If so, convert to signed.
1314 bool castIsSigned = Cmp.isSignedPredicate();
1316 // If the operand was a pointer, convert to a large integer type.
1317 const Type* OpTy = Operand->getType();
1318 if (isa<PointerType>(OpTy))
1319 OpTy = TD->getIntPtrType();
1322 printSimpleType(Out, OpTy, castIsSigned);
1324 writeOperand(Operand);
1328 // generateCompilerSpecificCode - This is where we add conditional compilation
1329 // directives to cater to specific compilers as need be.
1331 static void generateCompilerSpecificCode(std::ostream& Out) {
1332 // Alloca is hard to get, and we don't want to include stdlib.h here.
1333 Out << "/* get a declaration for alloca */\n"
1334 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1335 << "#define alloca(x) __builtin_alloca((x))\n"
1336 << "#define _alloca(x) __builtin_alloca((x))\n"
1337 << "#elif defined(__APPLE__)\n"
1338 << "extern void *__builtin_alloca(unsigned long);\n"
1339 << "#define alloca(x) __builtin_alloca(x)\n"
1340 << "#define longjmp _longjmp\n"
1341 << "#define setjmp _setjmp\n"
1342 << "#elif defined(__sun__)\n"
1343 << "#if defined(__sparcv9)\n"
1344 << "extern void *__builtin_alloca(unsigned long);\n"
1346 << "extern void *__builtin_alloca(unsigned int);\n"
1348 << "#define alloca(x) __builtin_alloca(x)\n"
1349 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)\n"
1350 << "#define alloca(x) __builtin_alloca(x)\n"
1351 << "#elif defined(_MSC_VER)\n"
1352 << "#define inline _inline\n"
1353 << "#define alloca(x) _alloca(x)\n"
1355 << "#include <alloca.h>\n"
1358 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1359 // If we aren't being compiled with GCC, just drop these attributes.
1360 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1361 << "#define __attribute__(X)\n"
1364 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1365 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1366 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1367 << "#elif defined(__GNUC__)\n"
1368 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1370 << "#define __EXTERNAL_WEAK__\n"
1373 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1374 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1375 << "#define __ATTRIBUTE_WEAK__\n"
1376 << "#elif defined(__GNUC__)\n"
1377 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1379 << "#define __ATTRIBUTE_WEAK__\n"
1382 // Add hidden visibility support. FIXME: APPLE_CC?
1383 Out << "#if defined(__GNUC__)\n"
1384 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1387 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1388 // From the GCC documentation:
1390 // double __builtin_nan (const char *str)
1392 // This is an implementation of the ISO C99 function nan.
1394 // Since ISO C99 defines this function in terms of strtod, which we do
1395 // not implement, a description of the parsing is in order. The string is
1396 // parsed as by strtol; that is, the base is recognized by leading 0 or
1397 // 0x prefixes. The number parsed is placed in the significand such that
1398 // the least significant bit of the number is at the least significant
1399 // bit of the significand. The number is truncated to fit the significand
1400 // field provided. The significand is forced to be a quiet NaN.
1402 // This function, if given a string literal, is evaluated early enough
1403 // that it is considered a compile-time constant.
1405 // float __builtin_nanf (const char *str)
1407 // Similar to __builtin_nan, except the return type is float.
1409 // double __builtin_inf (void)
1411 // Similar to __builtin_huge_val, except a warning is generated if the
1412 // target floating-point format does not support infinities. This
1413 // function is suitable for implementing the ISO C99 macro INFINITY.
1415 // float __builtin_inff (void)
1417 // Similar to __builtin_inf, except the return type is float.
1418 Out << "#ifdef __GNUC__\n"
1419 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1420 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1421 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1422 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1423 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1424 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1425 << "#define LLVM_PREFETCH(addr,rw,locality) "
1426 "__builtin_prefetch(addr,rw,locality)\n"
1427 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1428 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1429 << "#define LLVM_ASM __asm__\n"
1431 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1432 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1433 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1434 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1435 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1436 << "#define LLVM_INFF 0.0F /* Float */\n"
1437 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1438 << "#define __ATTRIBUTE_CTOR__\n"
1439 << "#define __ATTRIBUTE_DTOR__\n"
1440 << "#define LLVM_ASM(X)\n"
1443 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1444 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1445 << "#define __builtin_stack_restore(X) /* noop */\n"
1448 // Output target-specific code that should be inserted into main.
1449 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1452 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1453 /// the StaticTors set.
1454 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1455 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1456 if (!InitList) return;
1458 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1459 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1460 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1462 if (CS->getOperand(1)->isNullValue())
1463 return; // Found a null terminator, exit printing.
1464 Constant *FP = CS->getOperand(1);
1465 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1467 FP = CE->getOperand(0);
1468 if (Function *F = dyn_cast<Function>(FP))
1469 StaticTors.insert(F);
1473 enum SpecialGlobalClass {
1475 GlobalCtors, GlobalDtors,
1479 /// getGlobalVariableClass - If this is a global that is specially recognized
1480 /// by LLVM, return a code that indicates how we should handle it.
1481 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1482 // If this is a global ctors/dtors list, handle it now.
1483 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1484 if (GV->getName() == "llvm.global_ctors")
1486 else if (GV->getName() == "llvm.global_dtors")
1490 // Otherwise, it it is other metadata, don't print it. This catches things
1491 // like debug information.
1492 if (GV->getSection() == "llvm.metadata")
1499 bool CWriter::doInitialization(Module &M) {
1503 TD = new TargetData(&M);
1504 IL = new IntrinsicLowering(*TD);
1505 IL->AddPrototypes(M);
1507 // Ensure that all structure types have names...
1508 Mang = new Mangler(M);
1509 Mang->markCharUnacceptable('.');
1511 // Keep track of which functions are static ctors/dtors so they can have
1512 // an attribute added to their prototypes.
1513 std::set<Function*> StaticCtors, StaticDtors;
1514 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1516 switch (getGlobalVariableClass(I)) {
1519 FindStaticTors(I, StaticCtors);
1522 FindStaticTors(I, StaticDtors);
1527 // get declaration for alloca
1528 Out << "/* Provide Declarations */\n";
1529 Out << "#include <stdarg.h>\n"; // Varargs support
1530 Out << "#include <setjmp.h>\n"; // Unwind support
1531 generateCompilerSpecificCode(Out);
1533 // Provide a definition for `bool' if not compiling with a C++ compiler.
1535 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1537 << "\n\n/* Support for floating point constants */\n"
1538 << "typedef unsigned long long ConstantDoubleTy;\n"
1539 << "typedef unsigned int ConstantFloatTy;\n"
1540 << "typedef struct { unsigned long long f1; unsigned short f2; "
1541 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1542 // This is used for both kinds of 128-bit long double; meaning differs.
1543 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1544 " ConstantFP128Ty;\n"
1545 << "\n\n/* Global Declarations */\n";
1547 // First output all the declarations for the program, because C requires
1548 // Functions & globals to be declared before they are used.
1551 // Loop over the symbol table, emitting all named constants...
1552 printModuleTypes(M.getTypeSymbolTable());
1554 // Global variable declarations...
1555 if (!M.global_empty()) {
1556 Out << "\n/* External Global Variable Declarations */\n";
1557 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1560 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage())
1562 else if (I->hasDLLImportLinkage())
1563 Out << "__declspec(dllimport) ";
1565 continue; // Internal Global
1567 // Thread Local Storage
1568 if (I->isThreadLocal())
1571 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1573 if (I->hasExternalWeakLinkage())
1574 Out << " __EXTERNAL_WEAK__";
1579 // Function declarations
1580 Out << "\n/* Function Declarations */\n";
1581 Out << "double fmod(double, double);\n"; // Support for FP rem
1582 Out << "float fmodf(float, float);\n";
1583 Out << "long double fmodl(long double, long double);\n";
1585 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1586 // Don't print declarations for intrinsic functions.
1587 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
1588 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1589 if (I->hasExternalWeakLinkage())
1591 printFunctionSignature(I, true);
1592 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1593 Out << " __ATTRIBUTE_WEAK__";
1594 if (I->hasExternalWeakLinkage())
1595 Out << " __EXTERNAL_WEAK__";
1596 if (StaticCtors.count(I))
1597 Out << " __ATTRIBUTE_CTOR__";
1598 if (StaticDtors.count(I))
1599 Out << " __ATTRIBUTE_DTOR__";
1600 if (I->hasHiddenVisibility())
1601 Out << " __HIDDEN__";
1603 if (I->hasName() && I->getName()[0] == 1)
1604 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1610 // Output the global variable declarations
1611 if (!M.global_empty()) {
1612 Out << "\n\n/* Global Variable Declarations */\n";
1613 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1615 if (!I->isDeclaration()) {
1616 // Ignore special globals, such as debug info.
1617 if (getGlobalVariableClass(I))
1620 if (I->hasInternalLinkage())
1625 // Thread Local Storage
1626 if (I->isThreadLocal())
1629 printType(Out, I->getType()->getElementType(), false,
1632 if (I->hasLinkOnceLinkage())
1633 Out << " __attribute__((common))";
1634 else if (I->hasWeakLinkage())
1635 Out << " __ATTRIBUTE_WEAK__";
1636 else if (I->hasExternalWeakLinkage())
1637 Out << " __EXTERNAL_WEAK__";
1638 if (I->hasHiddenVisibility())
1639 Out << " __HIDDEN__";
1644 // Output the global variable definitions and contents...
1645 if (!M.global_empty()) {
1646 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1647 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1649 if (!I->isDeclaration()) {
1650 // Ignore special globals, such as debug info.
1651 if (getGlobalVariableClass(I))
1654 if (I->hasInternalLinkage())
1656 else if (I->hasDLLImportLinkage())
1657 Out << "__declspec(dllimport) ";
1658 else if (I->hasDLLExportLinkage())
1659 Out << "__declspec(dllexport) ";
1661 // Thread Local Storage
1662 if (I->isThreadLocal())
1665 printType(Out, I->getType()->getElementType(), false,
1667 if (I->hasLinkOnceLinkage())
1668 Out << " __attribute__((common))";
1669 else if (I->hasWeakLinkage())
1670 Out << " __ATTRIBUTE_WEAK__";
1672 if (I->hasHiddenVisibility())
1673 Out << " __HIDDEN__";
1675 // If the initializer is not null, emit the initializer. If it is null,
1676 // we try to avoid emitting large amounts of zeros. The problem with
1677 // this, however, occurs when the variable has weak linkage. In this
1678 // case, the assembler will complain about the variable being both weak
1679 // and common, so we disable this optimization.
1680 if (!I->getInitializer()->isNullValue()) {
1682 writeOperand(I->getInitializer());
1683 } else if (I->hasWeakLinkage()) {
1684 // We have to specify an initializer, but it doesn't have to be
1685 // complete. If the value is an aggregate, print out { 0 }, and let
1686 // the compiler figure out the rest of the zeros.
1688 if (isa<StructType>(I->getInitializer()->getType()) ||
1689 isa<ArrayType>(I->getInitializer()->getType()) ||
1690 isa<VectorType>(I->getInitializer()->getType())) {
1693 // Just print it out normally.
1694 writeOperand(I->getInitializer());
1702 Out << "\n\n/* Function Bodies */\n";
1704 // Emit some helper functions for dealing with FCMP instruction's
1706 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1707 Out << "return X == X && Y == Y; }\n";
1708 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1709 Out << "return X != X || Y != Y; }\n";
1710 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
1711 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
1712 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
1713 Out << "return X != Y; }\n";
1714 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
1715 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
1716 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
1717 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
1718 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
1719 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
1720 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
1721 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
1722 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
1723 Out << "return X == Y ; }\n";
1724 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
1725 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
1726 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
1727 Out << "return X < Y ; }\n";
1728 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
1729 Out << "return X > Y ; }\n";
1730 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
1731 Out << "return X <= Y ; }\n";
1732 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
1733 Out << "return X >= Y ; }\n";
1738 /// Output all floating point constants that cannot be printed accurately...
1739 void CWriter::printFloatingPointConstants(Function &F) {
1740 // Scan the module for floating point constants. If any FP constant is used
1741 // in the function, we want to redirect it here so that we do not depend on
1742 // the precision of the printed form, unless the printed form preserves
1745 static unsigned FPCounter = 0;
1746 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1748 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1749 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1750 !FPConstantMap.count(FPC)) {
1751 FPConstantMap[FPC] = FPCounter; // Number the FP constants
1753 if (FPC->getType() == Type::DoubleTy) {
1754 double Val = FPC->getValueAPF().convertToDouble();
1755 uint64_t i = FPC->getValueAPF().convertToAPInt().getZExtValue();
1756 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1757 << " = 0x" << std::hex << i << std::dec
1758 << "ULL; /* " << Val << " */\n";
1759 } else if (FPC->getType() == Type::FloatTy) {
1760 float Val = FPC->getValueAPF().convertToFloat();
1761 uint32_t i = (uint32_t)FPC->getValueAPF().convertToAPInt().
1763 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1764 << " = 0x" << std::hex << i << std::dec
1765 << "U; /* " << Val << " */\n";
1766 } else if (FPC->getType() == Type::X86_FP80Ty) {
1767 // api needed to prevent premature destruction
1768 APInt api = FPC->getValueAPF().convertToAPInt();
1769 const uint64_t *p = api.getRawData();
1770 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
1771 << " = { 0x" << std::hex
1772 << ((uint16_t)p[1] | (p[0] & 0xffffffffffffLL)<<16)
1773 << ", 0x" << (uint16_t)(p[0] >> 48) << ",0,0,0"
1774 << "}; /* Long double constant */\n" << std::dec;
1775 } else if (FPC->getType() == Type::PPC_FP128Ty) {
1776 APInt api = FPC->getValueAPF().convertToAPInt();
1777 const uint64_t *p = api.getRawData();
1778 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
1779 << " = { 0x" << std::hex
1780 << p[0] << ", 0x" << p[1]
1781 << "}; /* Long double constant */\n" << std::dec;
1784 assert(0 && "Unknown float type!");
1791 /// printSymbolTable - Run through symbol table looking for type names. If a
1792 /// type name is found, emit its declaration...
1794 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
1795 Out << "/* Helper union for bitcasts */\n";
1796 Out << "typedef union {\n";
1797 Out << " unsigned int Int32;\n";
1798 Out << " unsigned long long Int64;\n";
1799 Out << " float Float;\n";
1800 Out << " double Double;\n";
1801 Out << "} llvmBitCastUnion;\n";
1803 // We are only interested in the type plane of the symbol table.
1804 TypeSymbolTable::const_iterator I = TST.begin();
1805 TypeSymbolTable::const_iterator End = TST.end();
1807 // If there are no type names, exit early.
1808 if (I == End) return;
1810 // Print out forward declarations for structure types before anything else!
1811 Out << "/* Structure forward decls */\n";
1812 for (; I != End; ++I) {
1813 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1814 Out << Name << ";\n";
1815 TypeNames.insert(std::make_pair(I->second, Name));
1820 // Now we can print out typedefs. Above, we guaranteed that this can only be
1821 // for struct or opaque types.
1822 Out << "/* Typedefs */\n";
1823 for (I = TST.begin(); I != End; ++I) {
1824 std::string Name = "l_" + Mang->makeNameProper(I->first);
1826 printType(Out, I->second, false, Name);
1832 // Keep track of which structures have been printed so far...
1833 std::set<const StructType *> StructPrinted;
1835 // Loop over all structures then push them into the stack so they are
1836 // printed in the correct order.
1838 Out << "/* Structure contents */\n";
1839 for (I = TST.begin(); I != End; ++I)
1840 if (const StructType *STy = dyn_cast<StructType>(I->second))
1841 // Only print out used types!
1842 printContainedStructs(STy, StructPrinted);
1845 // Push the struct onto the stack and recursively push all structs
1846 // this one depends on.
1848 // TODO: Make this work properly with vector types
1850 void CWriter::printContainedStructs(const Type *Ty,
1851 std::set<const StructType*> &StructPrinted){
1852 // Don't walk through pointers.
1853 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
1855 // Print all contained types first.
1856 for (Type::subtype_iterator I = Ty->subtype_begin(),
1857 E = Ty->subtype_end(); I != E; ++I)
1858 printContainedStructs(*I, StructPrinted);
1860 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1861 // Check to see if we have already printed this struct.
1862 if (StructPrinted.insert(STy).second) {
1863 // Print structure type out.
1864 std::string Name = TypeNames[STy];
1865 printType(Out, STy, false, Name, true);
1871 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1872 /// isStructReturn - Should this function actually return a struct by-value?
1873 bool isStructReturn = F->isStructReturn();
1875 if (F->hasInternalLinkage()) Out << "static ";
1876 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1877 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
1878 switch (F->getCallingConv()) {
1879 case CallingConv::X86_StdCall:
1880 Out << "__stdcall ";
1882 case CallingConv::X86_FastCall:
1883 Out << "__fastcall ";
1887 // Loop over the arguments, printing them...
1888 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1889 const ParamAttrsList *PAL = F->getParamAttrs();
1891 std::stringstream FunctionInnards;
1893 // Print out the name...
1894 FunctionInnards << GetValueName(F) << '(';
1896 bool PrintedArg = false;
1897 if (!F->isDeclaration()) {
1898 if (!F->arg_empty()) {
1899 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1902 // If this is a struct-return function, don't print the hidden
1903 // struct-return argument.
1904 if (isStructReturn) {
1905 assert(I != E && "Invalid struct return function!");
1910 std::string ArgName;
1911 for (; I != E; ++I) {
1912 if (PrintedArg) FunctionInnards << ", ";
1913 if (I->hasName() || !Prototype)
1914 ArgName = GetValueName(I);
1917 const Type *ArgTy = I->getType();
1918 if (PAL && PAL->paramHasAttr(Idx, ParamAttr::ByVal)) {
1919 assert(isa<PointerType>(ArgTy));
1920 ArgTy = cast<PointerType>(ArgTy)->getElementType();
1921 const Value *Arg = &(*I);
1922 ByValParams.insert(Arg);
1924 printType(FunctionInnards, ArgTy,
1925 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt),
1932 // Loop over the arguments, printing them.
1933 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1936 // If this is a struct-return function, don't print the hidden
1937 // struct-return argument.
1938 if (isStructReturn) {
1939 assert(I != E && "Invalid struct return function!");
1944 for (; I != E; ++I) {
1945 if (PrintedArg) FunctionInnards << ", ";
1946 const Type *ArgTy = *I;
1947 if (PAL && PAL->paramHasAttr(Idx, ParamAttr::ByVal)) {
1948 assert(isa<PointerType>(ArgTy));
1949 ArgTy = cast<PointerType>(ArgTy)->getElementType();
1951 printType(FunctionInnards, ArgTy,
1952 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt));
1958 // Finish printing arguments... if this is a vararg function, print the ...,
1959 // unless there are no known types, in which case, we just emit ().
1961 if (FT->isVarArg() && PrintedArg) {
1962 if (PrintedArg) FunctionInnards << ", ";
1963 FunctionInnards << "..."; // Output varargs portion of signature!
1964 } else if (!FT->isVarArg() && !PrintedArg) {
1965 FunctionInnards << "void"; // ret() -> ret(void) in C.
1967 FunctionInnards << ')';
1969 // Get the return tpe for the function.
1971 if (!isStructReturn)
1972 RetTy = F->getReturnType();
1974 // If this is a struct-return function, print the struct-return type.
1975 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1978 // Print out the return type and the signature built above.
1979 printType(Out, RetTy,
1980 /*isSigned=*/ PAL && PAL->paramHasAttr(0, ParamAttr::SExt),
1981 FunctionInnards.str());
1984 static inline bool isFPIntBitCast(const Instruction &I) {
1985 if (!isa<BitCastInst>(I))
1987 const Type *SrcTy = I.getOperand(0)->getType();
1988 const Type *DstTy = I.getType();
1989 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
1990 (DstTy->isFloatingPoint() && SrcTy->isInteger());
1993 void CWriter::printFunction(Function &F) {
1994 /// isStructReturn - Should this function actually return a struct by-value?
1995 bool isStructReturn = F.isStructReturn();
1997 printFunctionSignature(&F, false);
2000 // If this is a struct return function, handle the result with magic.
2001 if (isStructReturn) {
2002 const Type *StructTy =
2003 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2005 printType(Out, StructTy, false, "StructReturn");
2006 Out << "; /* Struct return temporary */\n";
2009 printType(Out, F.arg_begin()->getType(), false,
2010 GetValueName(F.arg_begin()));
2011 Out << " = &StructReturn;\n";
2014 bool PrintedVar = false;
2016 // print local variable information for the function
2017 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2018 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2020 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2021 Out << "; /* Address-exposed local */\n";
2023 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
2025 printType(Out, I->getType(), false, GetValueName(&*I));
2028 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2030 printType(Out, I->getType(), false,
2031 GetValueName(&*I)+"__PHI_TEMPORARY");
2036 // We need a temporary for the BitCast to use so it can pluck a value out
2037 // of a union to do the BitCast. This is separate from the need for a
2038 // variable to hold the result of the BitCast.
2039 if (isFPIntBitCast(*I)) {
2040 Out << " llvmBitCastUnion " << GetValueName(&*I)
2041 << "__BITCAST_TEMPORARY;\n";
2049 if (F.hasExternalLinkage() && F.getName() == "main")
2050 Out << " CODE_FOR_MAIN();\n";
2052 // print the basic blocks
2053 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2054 if (Loop *L = LI->getLoopFor(BB)) {
2055 if (L->getHeader() == BB && L->getParentLoop() == 0)
2058 printBasicBlock(BB);
2065 void CWriter::printLoop(Loop *L) {
2066 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2067 << "' to make GCC happy */\n";
2068 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2069 BasicBlock *BB = L->getBlocks()[i];
2070 Loop *BBLoop = LI->getLoopFor(BB);
2072 printBasicBlock(BB);
2073 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2076 Out << " } while (1); /* end of syntactic loop '"
2077 << L->getHeader()->getName() << "' */\n";
2080 void CWriter::printBasicBlock(BasicBlock *BB) {
2082 // Don't print the label for the basic block if there are no uses, or if
2083 // the only terminator use is the predecessor basic block's terminator.
2084 // We have to scan the use list because PHI nodes use basic blocks too but
2085 // do not require a label to be generated.
2087 bool NeedsLabel = false;
2088 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2089 if (isGotoCodeNecessary(*PI, BB)) {
2094 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2096 // Output all of the instructions in the basic block...
2097 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2099 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2100 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
2109 // Don't emit prefix or suffix for the terminator...
2110 visit(*BB->getTerminator());
2114 // Specific Instruction type classes... note that all of the casts are
2115 // necessary because we use the instruction classes as opaque types...
2117 void CWriter::visitReturnInst(ReturnInst &I) {
2118 // If this is a struct return function, return the temporary struct.
2119 bool isStructReturn = I.getParent()->getParent()->isStructReturn();
2121 if (isStructReturn) {
2122 Out << " return StructReturn;\n";
2126 // Don't output a void return if this is the last basic block in the function
2127 if (I.getNumOperands() == 0 &&
2128 &*--I.getParent()->getParent()->end() == I.getParent() &&
2129 !I.getParent()->size() == 1) {
2134 if (I.getNumOperands()) {
2136 writeOperand(I.getOperand(0));
2141 void CWriter::visitSwitchInst(SwitchInst &SI) {
2144 writeOperand(SI.getOperand(0));
2145 Out << ") {\n default:\n";
2146 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2147 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2149 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2151 writeOperand(SI.getOperand(i));
2153 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2154 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2155 printBranchToBlock(SI.getParent(), Succ, 2);
2156 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
2162 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2163 Out << " /*UNREACHABLE*/;\n";
2166 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2167 /// FIXME: This should be reenabled, but loop reordering safe!!
2170 if (next(Function::iterator(From)) != Function::iterator(To))
2171 return true; // Not the direct successor, we need a goto.
2173 //isa<SwitchInst>(From->getTerminator())
2175 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2180 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2181 BasicBlock *Successor,
2183 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2184 PHINode *PN = cast<PHINode>(I);
2185 // Now we have to do the printing.
2186 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2187 if (!isa<UndefValue>(IV)) {
2188 Out << std::string(Indent, ' ');
2189 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2191 Out << "; /* for PHI node */\n";
2196 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2198 if (isGotoCodeNecessary(CurBB, Succ)) {
2199 Out << std::string(Indent, ' ') << " goto ";
2205 // Branch instruction printing - Avoid printing out a branch to a basic block
2206 // that immediately succeeds the current one.
2208 void CWriter::visitBranchInst(BranchInst &I) {
2210 if (I.isConditional()) {
2211 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2213 writeOperand(I.getCondition());
2216 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2217 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2219 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2220 Out << " } else {\n";
2221 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2222 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2225 // First goto not necessary, assume second one is...
2227 writeOperand(I.getCondition());
2230 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2231 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2236 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2237 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2242 // PHI nodes get copied into temporary values at the end of predecessor basic
2243 // blocks. We now need to copy these temporary values into the REAL value for
2245 void CWriter::visitPHINode(PHINode &I) {
2247 Out << "__PHI_TEMPORARY";
2251 void CWriter::visitBinaryOperator(Instruction &I) {
2252 // binary instructions, shift instructions, setCond instructions.
2253 assert(!isa<PointerType>(I.getType()));
2255 // We must cast the results of binary operations which might be promoted.
2256 bool needsCast = false;
2257 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
2258 || (I.getType() == Type::FloatTy)) {
2261 printType(Out, I.getType(), false);
2265 // If this is a negation operation, print it out as such. For FP, we don't
2266 // want to print "-0.0 - X".
2267 if (BinaryOperator::isNeg(&I)) {
2269 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2271 } else if (I.getOpcode() == Instruction::FRem) {
2272 // Output a call to fmod/fmodf instead of emitting a%b
2273 if (I.getType() == Type::FloatTy)
2275 else if (I.getType() == Type::DoubleTy)
2277 else // all 3 flavors of long double
2279 writeOperand(I.getOperand(0));
2281 writeOperand(I.getOperand(1));
2285 // Write out the cast of the instruction's value back to the proper type
2287 bool NeedsClosingParens = writeInstructionCast(I);
2289 // Certain instructions require the operand to be forced to a specific type
2290 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2291 // below for operand 1
2292 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2294 switch (I.getOpcode()) {
2295 case Instruction::Add: Out << " + "; break;
2296 case Instruction::Sub: Out << " - "; break;
2297 case Instruction::Mul: Out << " * "; break;
2298 case Instruction::URem:
2299 case Instruction::SRem:
2300 case Instruction::FRem: Out << " % "; break;
2301 case Instruction::UDiv:
2302 case Instruction::SDiv:
2303 case Instruction::FDiv: Out << " / "; break;
2304 case Instruction::And: Out << " & "; break;
2305 case Instruction::Or: Out << " | "; break;
2306 case Instruction::Xor: Out << " ^ "; break;
2307 case Instruction::Shl : Out << " << "; break;
2308 case Instruction::LShr:
2309 case Instruction::AShr: Out << " >> "; break;
2310 default: cerr << "Invalid operator type!" << I; abort();
2313 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2314 if (NeedsClosingParens)
2323 void CWriter::visitICmpInst(ICmpInst &I) {
2324 // We must cast the results of icmp which might be promoted.
2325 bool needsCast = false;
2327 // Write out the cast of the instruction's value back to the proper type
2329 bool NeedsClosingParens = writeInstructionCast(I);
2331 // Certain icmp predicate require the operand to be forced to a specific type
2332 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2333 // below for operand 1
2334 writeOperandWithCast(I.getOperand(0), I);
2336 switch (I.getPredicate()) {
2337 case ICmpInst::ICMP_EQ: Out << " == "; break;
2338 case ICmpInst::ICMP_NE: Out << " != "; break;
2339 case ICmpInst::ICMP_ULE:
2340 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2341 case ICmpInst::ICMP_UGE:
2342 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2343 case ICmpInst::ICMP_ULT:
2344 case ICmpInst::ICMP_SLT: Out << " < "; break;
2345 case ICmpInst::ICMP_UGT:
2346 case ICmpInst::ICMP_SGT: Out << " > "; break;
2347 default: cerr << "Invalid icmp predicate!" << I; abort();
2350 writeOperandWithCast(I.getOperand(1), I);
2351 if (NeedsClosingParens)
2359 void CWriter::visitFCmpInst(FCmpInst &I) {
2360 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2364 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2370 switch (I.getPredicate()) {
2371 default: assert(0 && "Illegal FCmp predicate");
2372 case FCmpInst::FCMP_ORD: op = "ord"; break;
2373 case FCmpInst::FCMP_UNO: op = "uno"; break;
2374 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2375 case FCmpInst::FCMP_UNE: op = "une"; break;
2376 case FCmpInst::FCMP_ULT: op = "ult"; break;
2377 case FCmpInst::FCMP_ULE: op = "ule"; break;
2378 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2379 case FCmpInst::FCMP_UGE: op = "uge"; break;
2380 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2381 case FCmpInst::FCMP_ONE: op = "one"; break;
2382 case FCmpInst::FCMP_OLT: op = "olt"; break;
2383 case FCmpInst::FCMP_OLE: op = "ole"; break;
2384 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2385 case FCmpInst::FCMP_OGE: op = "oge"; break;
2388 Out << "llvm_fcmp_" << op << "(";
2389 // Write the first operand
2390 writeOperand(I.getOperand(0));
2392 // Write the second operand
2393 writeOperand(I.getOperand(1));
2397 static const char * getFloatBitCastField(const Type *Ty) {
2398 switch (Ty->getTypeID()) {
2399 default: assert(0 && "Invalid Type");
2400 case Type::FloatTyID: return "Float";
2401 case Type::DoubleTyID: return "Double";
2402 case Type::IntegerTyID: {
2403 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2412 void CWriter::visitCastInst(CastInst &I) {
2413 const Type *DstTy = I.getType();
2414 const Type *SrcTy = I.getOperand(0)->getType();
2416 if (isFPIntBitCast(I)) {
2417 // These int<->float and long<->double casts need to be handled specially
2418 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2419 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2420 writeOperand(I.getOperand(0));
2421 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2422 << getFloatBitCastField(I.getType());
2424 printCast(I.getOpcode(), SrcTy, DstTy);
2425 if (I.getOpcode() == Instruction::SExt && SrcTy == Type::Int1Ty) {
2426 // Make sure we really get a sext from bool by subtracing the bool from 0
2429 // If it's a byval parameter being casted, then takes its address.
2430 bool isByVal = ByValParams.count(I.getOperand(0));
2432 assert(I.getOpcode() == Instruction::BitCast &&
2433 "ByVal aggregate parameter must ptr type");
2436 writeOperand(I.getOperand(0));
2437 if (DstTy == Type::Int1Ty &&
2438 (I.getOpcode() == Instruction::Trunc ||
2439 I.getOpcode() == Instruction::FPToUI ||
2440 I.getOpcode() == Instruction::FPToSI ||
2441 I.getOpcode() == Instruction::PtrToInt)) {
2442 // Make sure we really get a trunc to bool by anding the operand with 1
2449 void CWriter::visitSelectInst(SelectInst &I) {
2451 writeOperand(I.getCondition());
2453 writeOperand(I.getTrueValue());
2455 writeOperand(I.getFalseValue());
2460 void CWriter::lowerIntrinsics(Function &F) {
2461 // This is used to keep track of intrinsics that get generated to a lowered
2462 // function. We must generate the prototypes before the function body which
2463 // will only be expanded on first use (by the loop below).
2464 std::vector<Function*> prototypesToGen;
2466 // Examine all the instructions in this function to find the intrinsics that
2467 // need to be lowered.
2468 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2469 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2470 if (CallInst *CI = dyn_cast<CallInst>(I++))
2471 if (Function *F = CI->getCalledFunction())
2472 switch (F->getIntrinsicID()) {
2473 case Intrinsic::not_intrinsic:
2474 case Intrinsic::memory_barrier:
2475 case Intrinsic::vastart:
2476 case Intrinsic::vacopy:
2477 case Intrinsic::vaend:
2478 case Intrinsic::returnaddress:
2479 case Intrinsic::frameaddress:
2480 case Intrinsic::setjmp:
2481 case Intrinsic::longjmp:
2482 case Intrinsic::prefetch:
2483 case Intrinsic::dbg_stoppoint:
2484 case Intrinsic::powi:
2485 // We directly implement these intrinsics
2488 // If this is an intrinsic that directly corresponds to a GCC
2489 // builtin, we handle it.
2490 const char *BuiltinName = "";
2491 #define GET_GCC_BUILTIN_NAME
2492 #include "llvm/Intrinsics.gen"
2493 #undef GET_GCC_BUILTIN_NAME
2494 // If we handle it, don't lower it.
2495 if (BuiltinName[0]) break;
2497 // All other intrinsic calls we must lower.
2498 Instruction *Before = 0;
2499 if (CI != &BB->front())
2500 Before = prior(BasicBlock::iterator(CI));
2502 IL->LowerIntrinsicCall(CI);
2503 if (Before) { // Move iterator to instruction after call
2508 // If the intrinsic got lowered to another call, and that call has
2509 // a definition then we need to make sure its prototype is emitted
2510 // before any calls to it.
2511 if (CallInst *Call = dyn_cast<CallInst>(I))
2512 if (Function *NewF = Call->getCalledFunction())
2513 if (!NewF->isDeclaration())
2514 prototypesToGen.push_back(NewF);
2519 // We may have collected some prototypes to emit in the loop above.
2520 // Emit them now, before the function that uses them is emitted. But,
2521 // be careful not to emit them twice.
2522 std::vector<Function*>::iterator I = prototypesToGen.begin();
2523 std::vector<Function*>::iterator E = prototypesToGen.end();
2524 for ( ; I != E; ++I) {
2525 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2527 printFunctionSignature(*I, true);
2534 void CWriter::visitCallInst(CallInst &I) {
2535 //check if we have inline asm
2536 if (isInlineAsm(I)) {
2541 bool WroteCallee = false;
2543 // Handle intrinsic function calls first...
2544 if (Function *F = I.getCalledFunction())
2545 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
2548 // If this is an intrinsic that directly corresponds to a GCC
2549 // builtin, we emit it here.
2550 const char *BuiltinName = "";
2551 #define GET_GCC_BUILTIN_NAME
2552 #include "llvm/Intrinsics.gen"
2553 #undef GET_GCC_BUILTIN_NAME
2554 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2560 case Intrinsic::memory_barrier:
2561 Out << "0; __sync_syncronize()";
2563 case Intrinsic::vastart:
2566 Out << "va_start(*(va_list*)";
2567 writeOperand(I.getOperand(1));
2569 // Output the last argument to the enclosing function...
2570 if (I.getParent()->getParent()->arg_empty()) {
2571 cerr << "The C backend does not currently support zero "
2572 << "argument varargs functions, such as '"
2573 << I.getParent()->getParent()->getName() << "'!\n";
2576 writeOperand(--I.getParent()->getParent()->arg_end());
2579 case Intrinsic::vaend:
2580 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2581 Out << "0; va_end(*(va_list*)";
2582 writeOperand(I.getOperand(1));
2585 Out << "va_end(*(va_list*)0)";
2588 case Intrinsic::vacopy:
2590 Out << "va_copy(*(va_list*)";
2591 writeOperand(I.getOperand(1));
2592 Out << ", *(va_list*)";
2593 writeOperand(I.getOperand(2));
2596 case Intrinsic::returnaddress:
2597 Out << "__builtin_return_address(";
2598 writeOperand(I.getOperand(1));
2601 case Intrinsic::frameaddress:
2602 Out << "__builtin_frame_address(";
2603 writeOperand(I.getOperand(1));
2606 case Intrinsic::powi:
2607 Out << "__builtin_powi(";
2608 writeOperand(I.getOperand(1));
2610 writeOperand(I.getOperand(2));
2613 case Intrinsic::setjmp:
2614 Out << "setjmp(*(jmp_buf*)";
2615 writeOperand(I.getOperand(1));
2618 case Intrinsic::longjmp:
2619 Out << "longjmp(*(jmp_buf*)";
2620 writeOperand(I.getOperand(1));
2622 writeOperand(I.getOperand(2));
2625 case Intrinsic::prefetch:
2626 Out << "LLVM_PREFETCH((const void *)";
2627 writeOperand(I.getOperand(1));
2629 writeOperand(I.getOperand(2));
2631 writeOperand(I.getOperand(3));
2634 case Intrinsic::stacksave:
2635 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
2636 // to work around GCC bugs (see PR1809).
2637 Out << "0; *((void**)&" << GetValueName(&I)
2638 << ") = __builtin_stack_save()";
2640 case Intrinsic::dbg_stoppoint: {
2641 // If we use writeOperand directly we get a "u" suffix which is rejected
2643 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2647 << " \"" << SPI.getDirectory()
2648 << SPI.getFileName() << "\"\n";
2654 Value *Callee = I.getCalledValue();
2656 const PointerType *PTy = cast<PointerType>(Callee->getType());
2657 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2659 // If this is a call to a struct-return function, assign to the first
2660 // parameter instead of passing it to the call.
2661 const ParamAttrsList *PAL = I.getParamAttrs();
2662 bool hasByVal = I.hasByValArgument();
2663 bool isStructRet = I.isStructReturn();
2665 bool isByVal = ByValParams.count(I.getOperand(1));
2666 if (!isByVal) Out << "*(";
2667 writeOperand(I.getOperand(1));
2668 if (!isByVal) Out << ")";
2672 if (I.isTailCall()) Out << " /*tail*/ ";
2675 // If this is an indirect call to a struct return function, we need to cast
2676 // the pointer. Ditto for indirect calls with byval arguments.
2677 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
2679 // GCC is a real PITA. It does not permit codegening casts of functions to
2680 // function pointers if they are in a call (it generates a trap instruction
2681 // instead!). We work around this by inserting a cast to void* in between
2682 // the function and the function pointer cast. Unfortunately, we can't just
2683 // form the constant expression here, because the folder will immediately
2686 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2687 // that void* and function pointers have the same size. :( To deal with this
2688 // in the common case, we handle casts where the number of arguments passed
2691 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2693 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2699 // Ok, just cast the pointer type.
2702 printStructReturnPointerFunctionType(Out, PAL,
2703 cast<PointerType>(I.getCalledValue()->getType()));
2705 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
2707 printType(Out, I.getCalledValue()->getType());
2710 writeOperand(Callee);
2711 if (NeedsCast) Out << ')';
2716 unsigned NumDeclaredParams = FTy->getNumParams();
2718 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2720 if (isStructRet) { // Skip struct return argument.
2725 bool PrintedArg = false;
2726 for (; AI != AE; ++AI, ++ArgNo) {
2727 if (PrintedArg) Out << ", ";
2728 if (ArgNo < NumDeclaredParams &&
2729 (*AI)->getType() != FTy->getParamType(ArgNo)) {
2731 printType(Out, FTy->getParamType(ArgNo),
2732 /*isSigned=*/PAL && PAL->paramHasAttr(ArgNo+1, ParamAttr::SExt));
2735 // Check if the argument is expected to be passed by value.
2736 bool isOutByVal = PAL && PAL->paramHasAttr(ArgNo+1, ParamAttr::ByVal);
2737 // Check if this argument itself is passed in by reference.
2738 bool isInByVal = ByValParams.count(*AI);
2739 if (isOutByVal && !isInByVal)
2741 else if (!isOutByVal && isInByVal)
2744 if (isOutByVal ^ isInByVal)
2752 //This converts the llvm constraint string to something gcc is expecting.
2753 //TODO: work out platform independent constraints and factor those out
2754 // of the per target tables
2755 // handle multiple constraint codes
2756 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
2758 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
2760 const char** table = 0;
2762 //Grab the translation table from TargetAsmInfo if it exists
2765 const TargetMachineRegistry::entry* Match =
2766 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
2768 //Per platform Target Machines don't exist, so create it
2769 // this must be done only once
2770 const TargetMachine* TM = Match->CtorFn(*TheModule, "");
2771 TAsm = TM->getTargetAsmInfo();
2775 table = TAsm->getAsmCBE();
2777 //Search the translation table if it exists
2778 for (int i = 0; table && table[i]; i += 2)
2779 if (c.Codes[0] == table[i])
2782 //default is identity
2786 //TODO: import logic from AsmPrinter.cpp
2787 static std::string gccifyAsm(std::string asmstr) {
2788 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
2789 if (asmstr[i] == '\n')
2790 asmstr.replace(i, 1, "\\n");
2791 else if (asmstr[i] == '\t')
2792 asmstr.replace(i, 1, "\\t");
2793 else if (asmstr[i] == '$') {
2794 if (asmstr[i + 1] == '{') {
2795 std::string::size_type a = asmstr.find_first_of(':', i + 1);
2796 std::string::size_type b = asmstr.find_first_of('}', i + 1);
2797 std::string n = "%" +
2798 asmstr.substr(a + 1, b - a - 1) +
2799 asmstr.substr(i + 2, a - i - 2);
2800 asmstr.replace(i, b - i + 1, n);
2803 asmstr.replace(i, 1, "%");
2805 else if (asmstr[i] == '%')//grr
2806 { asmstr.replace(i, 1, "%%"); ++i;}
2811 //TODO: assumptions about what consume arguments from the call are likely wrong
2812 // handle communitivity
2813 void CWriter::visitInlineAsm(CallInst &CI) {
2814 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
2815 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
2816 std::vector<std::pair<std::string, Value*> > Input;
2817 std::vector<std::pair<std::string, Value*> > Output;
2818 std::string Clobber;
2819 int count = CI.getType() == Type::VoidTy ? 1 : 0;
2820 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
2821 E = Constraints.end(); I != E; ++I) {
2822 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
2824 InterpretASMConstraint(*I);
2827 assert(0 && "Unknown asm constraint");
2829 case InlineAsm::isInput: {
2831 Input.push_back(std::make_pair(c, count ? CI.getOperand(count) : &CI));
2832 ++count; //consume arg
2836 case InlineAsm::isOutput: {
2838 Output.push_back(std::make_pair("="+((I->isEarlyClobber ? "&" : "")+c),
2839 count ? CI.getOperand(count) : &CI));
2840 ++count; //consume arg
2844 case InlineAsm::isClobber: {
2846 Clobber += ",\"" + c + "\"";
2852 //fix up the asm string for gcc
2853 std::string asmstr = gccifyAsm(as->getAsmString());
2855 Out << "__asm__ volatile (\"" << asmstr << "\"\n";
2857 for (std::vector<std::pair<std::string, Value*> >::iterator I = Output.begin(),
2858 E = Output.end(); I != E; ++I) {
2859 Out << "\"" << I->first << "\"(";
2860 writeOperandRaw(I->second);
2866 for (std::vector<std::pair<std::string, Value*> >::iterator I = Input.begin(),
2867 E = Input.end(); I != E; ++I) {
2868 Out << "\"" << I->first << "\"(";
2869 writeOperandRaw(I->second);
2875 Out << "\n :" << Clobber.substr(1);
2879 void CWriter::visitMallocInst(MallocInst &I) {
2880 assert(0 && "lowerallocations pass didn't work!");
2883 void CWriter::visitAllocaInst(AllocaInst &I) {
2885 printType(Out, I.getType());
2886 Out << ") alloca(sizeof(";
2887 printType(Out, I.getType()->getElementType());
2889 if (I.isArrayAllocation()) {
2891 writeOperand(I.getOperand(0));
2896 void CWriter::visitFreeInst(FreeInst &I) {
2897 assert(0 && "lowerallocations pass didn't work!");
2900 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2901 gep_type_iterator E) {
2902 bool HasImplicitAddress = false;
2903 // If accessing a global value with no indexing, avoid *(&GV) syndrome
2904 if (isa<GlobalValue>(Ptr)) {
2905 HasImplicitAddress = true;
2906 } else if (isDirectAlloca(Ptr)) {
2907 HasImplicitAddress = true;
2911 if (!HasImplicitAddress)
2912 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
2914 writeOperandInternal(Ptr);
2918 const Constant *CI = dyn_cast<Constant>(I.getOperand());
2919 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2922 writeOperandInternal(Ptr);
2924 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
2926 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
2929 assert((!HasImplicitAddress || (CI && CI->isNullValue())) &&
2930 "Can only have implicit address with direct accessing");
2932 if (HasImplicitAddress) {
2934 } else if (CI && CI->isNullValue()) {
2935 gep_type_iterator TmpI = I; ++TmpI;
2937 // Print out the -> operator if possible...
2938 if (TmpI != E && isa<StructType>(*TmpI)) {
2939 // Check if it's actually an aggregate parameter passed by value.
2940 bool isByVal = ByValParams.count(Ptr);
2941 Out << ((HasImplicitAddress || isByVal) ? "." : "->");
2942 Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
2948 if (isa<StructType>(*I)) {
2949 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
2952 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
2957 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
2958 bool IsVolatile, unsigned Alignment) {
2960 bool IsUnaligned = Alignment &&
2961 Alignment < TD->getABITypeAlignment(OperandType);
2965 if (IsVolatile || IsUnaligned) {
2968 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
2969 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
2972 if (IsVolatile) Out << "volatile ";
2978 writeOperand(Operand);
2980 if (IsVolatile || IsUnaligned) {
2987 void CWriter::visitLoadInst(LoadInst &I) {
2989 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
2994 void CWriter::visitStoreInst(StoreInst &I) {
2996 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
2997 I.isVolatile(), I.getAlignment());
2999 Value *Operand = I.getOperand(0);
3000 Constant *BitMask = 0;
3001 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3002 if (!ITy->isPowerOf2ByteWidth())
3003 // We have a bit width that doesn't match an even power-of-2 byte
3004 // size. Consequently we must & the value with the type's bit mask
3005 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
3008 writeOperand(Operand);
3011 printConstant(BitMask);
3016 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3018 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
3022 void CWriter::visitVAArgInst(VAArgInst &I) {
3023 Out << "va_arg(*(va_list*)";
3024 writeOperand(I.getOperand(0));
3026 printType(Out, I.getType());
3030 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3031 const Type *EltTy = I.getType()->getElementType();
3032 writeOperand(I.getOperand(0));
3035 printType(Out, PointerType::getUnqual(EltTy));
3036 Out << ")(&" << GetValueName(&I) << "))[";
3037 writeOperand(I.getOperand(1));
3039 writeOperand(I.getOperand(2));
3043 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3044 // We know that our operand is not inlined.
3047 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3048 printType(Out, PointerType::getUnqual(EltTy));
3049 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3050 writeOperand(I.getOperand(1));
3056 //===----------------------------------------------------------------------===//
3057 // External Interface declaration
3058 //===----------------------------------------------------------------------===//
3060 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
3062 CodeGenFileType FileType,
3064 if (FileType != TargetMachine::AssemblyFile) return true;
3066 PM.add(createGCLoweringPass());
3067 PM.add(createLowerAllocationsPass(true));
3068 PM.add(createLowerInvokePass());
3069 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3070 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3071 PM.add(new CWriter(o));
3072 PM.add(createCollectorMetadataDeleter());