1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library converts LLVM code to C code, compilable by GCC and other C
13 //===----------------------------------------------------------------------===//
15 #include "CTargetMachine.h"
16 #include "llvm/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/SymbolTable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Analysis/ConstantsScanner.h"
27 #include "llvm/Analysis/FindUsedTypes.h"
28 #include "llvm/Analysis/LoopInfo.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Target/TargetMachineRegistry.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/GetElementPtrTypeIterator.h"
35 #include "llvm/Support/InstVisitor.h"
36 #include "llvm/Support/Mangler.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Config/config.h"
49 // Register the target.
50 RegisterTarget<CTargetMachine> X("c", " C backend");
52 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
53 /// any unnamed structure types that are used by the program, and merges
54 /// external functions with the same name.
56 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
57 void getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired<FindUsedTypes>();
61 virtual const char *getPassName() const {
62 return "C backend type canonicalizer";
65 virtual bool runOnModule(Module &M);
68 /// CWriter - This class is the main chunk of code that converts an LLVM
69 /// module to a C translation unit.
70 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
75 const Module *TheModule;
76 std::map<const Type *, std::string> TypeNames;
78 std::map<const ConstantFP *, unsigned> FPConstantMap;
80 CWriter(std::ostream &o) : Out(o) {}
82 virtual const char *getPassName() const { return "C backend"; }
84 void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<LoopInfo>();
89 virtual bool doInitialization(Module &M);
91 bool runOnFunction(Function &F) {
92 LI = &getAnalysis<LoopInfo>();
94 // Get rid of intrinsics we can't handle.
97 // Output all floating point constants that cannot be printed accurately.
98 printFloatingPointConstants(F);
100 // Ensure that no local symbols conflict with global symbols.
101 F.renameLocalSymbols();
104 FPConstantMap.clear();
108 virtual bool doFinalization(Module &M) {
115 std::ostream &printType(std::ostream &Out, const Type *Ty,
116 const std::string &VariableName = "",
117 bool IgnoreName = false);
119 void printStructReturnPointerFunctionType(std::ostream &Out,
120 const PointerType *Ty);
122 void writeOperand(Value *Operand);
123 void writeOperandInternal(Value *Operand);
124 void writeOperandWithCast(Value* Operand, unsigned Opcode);
125 bool writeInstructionCast(const Instruction &I);
128 void lowerIntrinsics(Function &F);
130 void printModule(Module *M);
131 void printModuleTypes(const SymbolTable &ST);
132 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
133 void printFloatingPointConstants(Function &F);
134 void printFunctionSignature(const Function *F, bool Prototype);
136 void printFunction(Function &);
137 void printBasicBlock(BasicBlock *BB);
138 void printLoop(Loop *L);
140 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
141 void printConstant(Constant *CPV);
142 void printConstantWithCast(Constant *CPV, unsigned Opcode);
143 bool printConstExprCast(const ConstantExpr *CE);
144 void printConstantArray(ConstantArray *CPA);
145 void printConstantPacked(ConstantPacked *CP);
147 // isInlinableInst - Attempt to inline instructions into their uses to build
148 // trees as much as possible. To do this, we have to consistently decide
149 // what is acceptable to inline, so that variable declarations don't get
150 // printed and an extra copy of the expr is not emitted.
152 static bool isInlinableInst(const Instruction &I) {
153 // Always inline setcc instructions, even if they are shared by multiple
154 // expressions. GCC generates horrible code if we don't.
155 if (isa<SetCondInst>(I)) return true;
157 // Must be an expression, must be used exactly once. If it is dead, we
158 // emit it inline where it would go.
159 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
160 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
161 isa<LoadInst>(I) || isa<VAArgInst>(I))
162 // Don't inline a load across a store or other bad things!
165 // Only inline instruction it it's use is in the same BB as the inst.
166 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
169 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
170 // variables which are accessed with the & operator. This causes GCC to
171 // generate significantly better code than to emit alloca calls directly.
173 static const AllocaInst *isDirectAlloca(const Value *V) {
174 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
175 if (!AI) return false;
176 if (AI->isArrayAllocation())
177 return 0; // FIXME: we can also inline fixed size array allocas!
178 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
183 // Instruction visitation functions
184 friend class InstVisitor<CWriter>;
186 void visitReturnInst(ReturnInst &I);
187 void visitBranchInst(BranchInst &I);
188 void visitSwitchInst(SwitchInst &I);
189 void visitInvokeInst(InvokeInst &I) {
190 assert(0 && "Lowerinvoke pass didn't work!");
193 void visitUnwindInst(UnwindInst &I) {
194 assert(0 && "Lowerinvoke pass didn't work!");
196 void visitUnreachableInst(UnreachableInst &I);
198 void visitPHINode(PHINode &I);
199 void visitBinaryOperator(Instruction &I);
201 void visitCastInst (CastInst &I);
202 void visitSelectInst(SelectInst &I);
203 void visitCallInst (CallInst &I);
204 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
206 void visitMallocInst(MallocInst &I);
207 void visitAllocaInst(AllocaInst &I);
208 void visitFreeInst (FreeInst &I);
209 void visitLoadInst (LoadInst &I);
210 void visitStoreInst (StoreInst &I);
211 void visitGetElementPtrInst(GetElementPtrInst &I);
212 void visitVAArgInst (VAArgInst &I);
214 void visitInstruction(Instruction &I) {
215 std::cerr << "C Writer does not know about " << I;
219 void outputLValue(Instruction *I) {
220 Out << " " << Mang->getValueName(I) << " = ";
223 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
224 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
225 BasicBlock *Successor, unsigned Indent);
226 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
228 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
229 gep_type_iterator E);
233 /// This method inserts names for any unnamed structure types that are used by
234 /// the program, and removes names from structure types that are not used by the
237 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
238 // Get a set of types that are used by the program...
239 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
241 // Loop over the module symbol table, removing types from UT that are
242 // already named, and removing names for types that are not used.
244 SymbolTable &MST = M.getSymbolTable();
245 for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
247 SymbolTable::type_iterator I = TI++;
249 // If this is not used, remove it from the symbol table.
250 std::set<const Type *>::iterator UTI = UT.find(I->second);
254 UT.erase(UTI); // Only keep one name for this type.
257 // UT now contains types that are not named. Loop over it, naming
260 bool Changed = false;
261 unsigned RenameCounter = 0;
262 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
264 if (const StructType *ST = dyn_cast<StructType>(*I)) {
265 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
271 // Loop over all external functions and globals. If we have two with
272 // identical names, merge them.
273 // FIXME: This code should disappear when we don't allow values with the same
274 // names when they have different types!
275 std::map<std::string, GlobalValue*> ExtSymbols;
276 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
278 if (GV->isExternal() && GV->hasName()) {
279 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
280 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
282 // Found a conflict, replace this global with the previous one.
283 GlobalValue *OldGV = X.first->second;
284 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
285 GV->eraseFromParent();
290 // Do the same for globals.
291 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
293 GlobalVariable *GV = I++;
294 if (GV->isExternal() && GV->hasName()) {
295 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
296 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
298 // Found a conflict, replace this global with the previous one.
299 GlobalValue *OldGV = X.first->second;
300 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
301 GV->eraseFromParent();
310 /// printStructReturnPointerFunctionType - This is like printType for a struct
311 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
312 /// print it as "Struct (*)(...)", for struct return functions.
313 void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
314 const PointerType *TheTy) {
315 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
316 std::stringstream FunctionInnards;
317 FunctionInnards << " (*) (";
318 bool PrintedType = false;
320 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
321 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
322 for (++I; I != E; ++I) {
324 FunctionInnards << ", ";
325 printType(FunctionInnards, *I, "");
328 if (FTy->isVarArg()) {
330 FunctionInnards << ", ...";
331 } else if (!PrintedType) {
332 FunctionInnards << "void";
334 FunctionInnards << ')';
335 std::string tstr = FunctionInnards.str();
336 printType(Out, RetTy, tstr);
340 // Pass the Type* and the variable name and this prints out the variable
343 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
344 const std::string &NameSoFar,
346 if (Ty->isPrimitiveType())
347 switch (Ty->getTypeID()) {
348 case Type::VoidTyID: return Out << "void " << NameSoFar;
349 case Type::BoolTyID: return Out << "bool " << NameSoFar;
350 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
351 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
352 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
353 case Type::ShortTyID: return Out << "short " << NameSoFar;
354 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
355 case Type::IntTyID: return Out << "int " << NameSoFar;
356 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
357 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
358 case Type::FloatTyID: return Out << "float " << NameSoFar;
359 case Type::DoubleTyID: return Out << "double " << NameSoFar;
361 std::cerr << "Unknown primitive type: " << *Ty << "\n";
365 // Check to see if the type is named.
366 if (!IgnoreName || isa<OpaqueType>(Ty)) {
367 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
368 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
371 switch (Ty->getTypeID()) {
372 case Type::FunctionTyID: {
373 const FunctionType *FTy = cast<FunctionType>(Ty);
374 std::stringstream FunctionInnards;
375 FunctionInnards << " (" << NameSoFar << ") (";
376 for (FunctionType::param_iterator I = FTy->param_begin(),
377 E = FTy->param_end(); I != E; ++I) {
378 if (I != FTy->param_begin())
379 FunctionInnards << ", ";
380 printType(FunctionInnards, *I, "");
382 if (FTy->isVarArg()) {
383 if (FTy->getNumParams())
384 FunctionInnards << ", ...";
385 } else if (!FTy->getNumParams()) {
386 FunctionInnards << "void";
388 FunctionInnards << ')';
389 std::string tstr = FunctionInnards.str();
390 printType(Out, FTy->getReturnType(), tstr);
393 case Type::StructTyID: {
394 const StructType *STy = cast<StructType>(Ty);
395 Out << NameSoFar + " {\n";
397 for (StructType::element_iterator I = STy->element_begin(),
398 E = STy->element_end(); I != E; ++I) {
400 printType(Out, *I, "field" + utostr(Idx++));
406 case Type::PointerTyID: {
407 const PointerType *PTy = cast<PointerType>(Ty);
408 std::string ptrName = "*" + NameSoFar;
410 if (isa<ArrayType>(PTy->getElementType()) ||
411 isa<PackedType>(PTy->getElementType()))
412 ptrName = "(" + ptrName + ")";
414 return printType(Out, PTy->getElementType(), ptrName);
417 case Type::ArrayTyID: {
418 const ArrayType *ATy = cast<ArrayType>(Ty);
419 unsigned NumElements = ATy->getNumElements();
420 if (NumElements == 0) NumElements = 1;
421 return printType(Out, ATy->getElementType(),
422 NameSoFar + "[" + utostr(NumElements) + "]");
425 case Type::PackedTyID: {
426 const PackedType *PTy = cast<PackedType>(Ty);
427 unsigned NumElements = PTy->getNumElements();
428 if (NumElements == 0) NumElements = 1;
429 return printType(Out, PTy->getElementType(),
430 NameSoFar + "[" + utostr(NumElements) + "]");
433 case Type::OpaqueTyID: {
434 static int Count = 0;
435 std::string TyName = "struct opaque_" + itostr(Count++);
436 assert(TypeNames.find(Ty) == TypeNames.end());
437 TypeNames[Ty] = TyName;
438 return Out << TyName << ' ' << NameSoFar;
441 assert(0 && "Unhandled case in getTypeProps!");
448 void CWriter::printConstantArray(ConstantArray *CPA) {
450 // As a special case, print the array as a string if it is an array of
451 // ubytes or an array of sbytes with positive values.
453 const Type *ETy = CPA->getType()->getElementType();
454 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
456 // Make sure the last character is a null char, as automatically added by C
457 if (isString && (CPA->getNumOperands() == 0 ||
458 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
463 // Keep track of whether the last number was a hexadecimal escape
464 bool LastWasHex = false;
466 // Do not include the last character, which we know is null
467 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
468 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
470 // Print it out literally if it is a printable character. The only thing
471 // to be careful about is when the last letter output was a hex escape
472 // code, in which case we have to be careful not to print out hex digits
473 // explicitly (the C compiler thinks it is a continuation of the previous
474 // character, sheesh...)
476 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
478 if (C == '"' || C == '\\')
485 case '\n': Out << "\\n"; break;
486 case '\t': Out << "\\t"; break;
487 case '\r': Out << "\\r"; break;
488 case '\v': Out << "\\v"; break;
489 case '\a': Out << "\\a"; break;
490 case '\"': Out << "\\\""; break;
491 case '\'': Out << "\\\'"; break;
494 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
495 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
504 if (CPA->getNumOperands()) {
506 printConstant(cast<Constant>(CPA->getOperand(0)));
507 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
509 printConstant(cast<Constant>(CPA->getOperand(i)));
516 void CWriter::printConstantPacked(ConstantPacked *CP) {
518 if (CP->getNumOperands()) {
520 printConstant(cast<Constant>(CP->getOperand(0)));
521 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
523 printConstant(cast<Constant>(CP->getOperand(i)));
529 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
530 // textually as a double (rather than as a reference to a stack-allocated
531 // variable). We decide this by converting CFP to a string and back into a
532 // double, and then checking whether the conversion results in a bit-equal
533 // double to the original value of CFP. This depends on us and the target C
534 // compiler agreeing on the conversion process (which is pretty likely since we
535 // only deal in IEEE FP).
537 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
538 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
540 sprintf(Buffer, "%a", CFP->getValue());
542 if (!strncmp(Buffer, "0x", 2) ||
543 !strncmp(Buffer, "-0x", 3) ||
544 !strncmp(Buffer, "+0x", 3))
545 return atof(Buffer) == CFP->getValue();
548 std::string StrVal = ftostr(CFP->getValue());
550 while (StrVal[0] == ' ')
551 StrVal.erase(StrVal.begin());
553 // Check to make sure that the stringized number is not some string like "Inf"
554 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
555 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
556 ((StrVal[0] == '-' || StrVal[0] == '+') &&
557 (StrVal[1] >= '0' && StrVal[1] <= '9')))
558 // Reparse stringized version!
559 return atof(StrVal.c_str()) == CFP->getValue();
564 /// Print out the casting for a cast operation. This does the double casting
565 /// necessary for conversion to the destination type, if necessary.
566 /// @returns true if a closing paren is necessary
567 /// @brief Print a cast
568 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
570 printType(Out, DstTy);
573 case Instruction::UIToFP:
574 case Instruction::ZExt:
575 if (SrcTy->isSigned()) {
577 printType(Out, SrcTy->getUnsignedVersion());
581 case Instruction::SIToFP:
582 case Instruction::SExt:
583 if (SrcTy->isUnsigned()) {
585 printType(Out, SrcTy->getSignedVersion());
589 case Instruction::IntToPtr:
590 case Instruction::PtrToInt:
591 // Avoid "cast to pointer from integer of different size" warnings
592 Out << "(unsigned long)";
594 case Instruction::Trunc:
595 case Instruction::BitCast:
596 case Instruction::FPExt:
597 case Instruction::FPTrunc:
598 case Instruction::FPToSI:
599 case Instruction::FPToUI:
605 // printConstant - The LLVM Constant to C Constant converter.
606 void CWriter::printConstant(Constant *CPV) {
607 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
608 switch (CE->getOpcode()) {
609 case Instruction::Trunc:
610 case Instruction::ZExt:
611 case Instruction::SExt:
612 case Instruction::FPTrunc:
613 case Instruction::FPExt:
614 case Instruction::UIToFP:
615 case Instruction::SIToFP:
616 case Instruction::FPToUI:
617 case Instruction::FPToSI:
618 case Instruction::PtrToInt:
619 case Instruction::IntToPtr:
620 case Instruction::BitCast:
622 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
623 if (CE->getOpcode() == Instruction::SExt &&
624 CE->getOperand(0)->getType() == Type::BoolTy) {
625 // Make sure we really sext from bool here by subtracting from 0
628 printConstant(CE->getOperand(0));
629 if (CE->getOpcode() == Instruction::Trunc &&
630 CE->getType() == Type::BoolTy) {
631 // Make sure we really truncate to bool here by anding with 1
637 case Instruction::GetElementPtr:
639 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
643 case Instruction::Select:
645 printConstant(CE->getOperand(0));
647 printConstant(CE->getOperand(1));
649 printConstant(CE->getOperand(2));
652 case Instruction::Add:
653 case Instruction::Sub:
654 case Instruction::Mul:
655 case Instruction::SDiv:
656 case Instruction::UDiv:
657 case Instruction::FDiv:
658 case Instruction::URem:
659 case Instruction::SRem:
660 case Instruction::FRem:
661 case Instruction::And:
662 case Instruction::Or:
663 case Instruction::Xor:
664 case Instruction::SetEQ:
665 case Instruction::SetNE:
666 case Instruction::SetLT:
667 case Instruction::SetLE:
668 case Instruction::SetGT:
669 case Instruction::SetGE:
670 case Instruction::Shl:
671 case Instruction::LShr:
672 case Instruction::AShr:
675 bool NeedsClosingParens = printConstExprCast(CE);
676 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
677 switch (CE->getOpcode()) {
678 case Instruction::Add: Out << " + "; break;
679 case Instruction::Sub: Out << " - "; break;
680 case Instruction::Mul: Out << " * "; break;
681 case Instruction::URem:
682 case Instruction::SRem:
683 case Instruction::FRem: Out << " % "; break;
684 case Instruction::UDiv:
685 case Instruction::SDiv:
686 case Instruction::FDiv: Out << " / "; break;
687 case Instruction::And: Out << " & "; break;
688 case Instruction::Or: Out << " | "; break;
689 case Instruction::Xor: Out << " ^ "; break;
690 case Instruction::SetEQ: Out << " == "; break;
691 case Instruction::SetNE: Out << " != "; break;
692 case Instruction::SetLT: Out << " < "; break;
693 case Instruction::SetLE: Out << " <= "; break;
694 case Instruction::SetGT: Out << " > "; break;
695 case Instruction::SetGE: Out << " >= "; break;
696 case Instruction::Shl: Out << " << "; break;
697 case Instruction::LShr:
698 case Instruction::AShr: Out << " >> "; break;
699 default: assert(0 && "Illegal opcode here!");
701 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
702 if (NeedsClosingParens)
709 std::cerr << "CWriter Error: Unhandled constant expression: "
713 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
715 printType(Out, CPV->getType());
716 Out << ")/*UNDEF*/0)";
720 switch (CPV->getType()->getTypeID()) {
722 Out << (cast<ConstantBool>(CPV)->getValue() ? '1' : '0');
724 case Type::SByteTyID:
725 case Type::ShortTyID:
726 Out << cast<ConstantInt>(CPV)->getSExtValue();
729 if ((int)cast<ConstantInt>(CPV)->getSExtValue() == (int)0x80000000)
730 Out << "((int)0x80000000U)"; // Handle MININT specially to avoid warning
732 Out << cast<ConstantInt>(CPV)->getSExtValue();
736 if (cast<ConstantInt>(CPV)->isMinValue())
737 Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
739 Out << cast<ConstantInt>(CPV)->getSExtValue() << "ll";
742 case Type::UByteTyID:
743 case Type::UShortTyID:
744 Out << cast<ConstantInt>(CPV)->getZExtValue();
747 Out << cast<ConstantInt>(CPV)->getZExtValue() << 'u';
749 case Type::ULongTyID:
750 Out << cast<ConstantInt>(CPV)->getZExtValue() << "ull";
753 case Type::FloatTyID:
754 case Type::DoubleTyID: {
755 ConstantFP *FPC = cast<ConstantFP>(CPV);
756 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
757 if (I != FPConstantMap.end()) {
758 // Because of FP precision problems we must load from a stack allocated
759 // value that holds the value in hex.
760 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
761 << "*)&FPConstant" << I->second << ')';
763 if (IsNAN(FPC->getValue())) {
766 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
768 const unsigned long QuietNaN = 0x7ff8UL;
769 //const unsigned long SignalNaN = 0x7ff4UL;
771 // We need to grab the first part of the FP #
774 uint64_t ll = DoubleToBits(FPC->getValue());
775 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
777 std::string Num(&Buffer[0], &Buffer[6]);
778 unsigned long Val = strtoul(Num.c_str(), 0, 16);
780 if (FPC->getType() == Type::FloatTy)
781 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
782 << Buffer << "\") /*nan*/ ";
784 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
785 << Buffer << "\") /*nan*/ ";
786 } else if (IsInf(FPC->getValue())) {
788 if (FPC->getValue() < 0) Out << '-';
789 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
793 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
794 // Print out the constant as a floating point number.
796 sprintf(Buffer, "%a", FPC->getValue());
799 Num = ftostr(FPC->getValue());
807 case Type::ArrayTyID:
808 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
809 const ArrayType *AT = cast<ArrayType>(CPV->getType());
811 if (AT->getNumElements()) {
813 Constant *CZ = Constant::getNullValue(AT->getElementType());
815 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
822 printConstantArray(cast<ConstantArray>(CPV));
826 case Type::PackedTyID:
827 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
828 const PackedType *AT = cast<PackedType>(CPV->getType());
830 if (AT->getNumElements()) {
832 Constant *CZ = Constant::getNullValue(AT->getElementType());
834 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
841 printConstantPacked(cast<ConstantPacked>(CPV));
845 case Type::StructTyID:
846 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
847 const StructType *ST = cast<StructType>(CPV->getType());
849 if (ST->getNumElements()) {
851 printConstant(Constant::getNullValue(ST->getElementType(0)));
852 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
854 printConstant(Constant::getNullValue(ST->getElementType(i)));
860 if (CPV->getNumOperands()) {
862 printConstant(cast<Constant>(CPV->getOperand(0)));
863 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
865 printConstant(cast<Constant>(CPV->getOperand(i)));
872 case Type::PointerTyID:
873 if (isa<ConstantPointerNull>(CPV)) {
875 printType(Out, CPV->getType());
876 Out << ")/*NULL*/0)";
878 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
884 std::cerr << "Unknown constant type: " << *CPV << "\n";
889 // Some constant expressions need to be casted back to the original types
890 // because their operands were casted to the expected type. This function takes
891 // care of detecting that case and printing the cast for the ConstantExpr.
892 bool CWriter::printConstExprCast(const ConstantExpr* CE) {
893 bool NeedsExplicitCast = false;
894 const Type *Ty = CE->getOperand(0)->getType();
895 switch (CE->getOpcode()) {
896 case Instruction::LShr:
897 case Instruction::URem:
898 case Instruction::UDiv:
899 NeedsExplicitCast = Ty->isSigned(); break;
900 case Instruction::AShr:
901 case Instruction::SRem:
902 case Instruction::SDiv:
903 NeedsExplicitCast = Ty->isUnsigned(); break;
904 case Instruction::ZExt:
905 case Instruction::SExt:
906 case Instruction::Trunc:
907 case Instruction::FPTrunc:
908 case Instruction::FPExt:
909 case Instruction::UIToFP:
910 case Instruction::SIToFP:
911 case Instruction::FPToUI:
912 case Instruction::FPToSI:
913 case Instruction::PtrToInt:
914 case Instruction::IntToPtr:
915 case Instruction::BitCast:
917 NeedsExplicitCast = true;
921 if (NeedsExplicitCast) {
926 return NeedsExplicitCast;
929 // Print a constant assuming that it is the operand for a given Opcode. The
930 // opcodes that care about sign need to cast their operands to the expected
931 // type before the operation proceeds. This function does the casting.
932 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
934 // Extract the operand's type, we'll need it.
935 const Type* OpTy = CPV->getType();
937 // Indicate whether to do the cast or not.
938 bool shouldCast = false;
940 // Based on the Opcode for which this Constant is being written, determine
941 // the new type to which the operand should be casted by setting the value
942 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
946 // for most instructions, it doesn't matter
948 case Instruction::LShr:
949 case Instruction::UDiv:
950 case Instruction::URem:
951 // For UDiv/URem get correct type
952 if (OpTy->isSigned()) {
953 OpTy = OpTy->getUnsignedVersion();
957 case Instruction::AShr:
958 case Instruction::SDiv:
959 case Instruction::SRem:
960 // For SDiv/SRem get correct type
961 if (OpTy->isUnsigned()) {
962 OpTy = OpTy->getSignedVersion();
968 // Write out the casted constant if we should, otherwise just write the
972 printType(Out, OpTy);
981 void CWriter::writeOperandInternal(Value *Operand) {
982 if (Instruction *I = dyn_cast<Instruction>(Operand))
983 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
984 // Should we inline this instruction to build a tree?
991 Constant* CPV = dyn_cast<Constant>(Operand);
992 if (CPV && !isa<GlobalValue>(CPV)) {
995 Out << Mang->getValueName(Operand);
999 void CWriter::writeOperand(Value *Operand) {
1000 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1001 Out << "(&"; // Global variables are referenced as their addresses by llvm
1003 writeOperandInternal(Operand);
1005 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1009 // Some instructions need to have their result value casted back to the
1010 // original types because their operands were casted to the expected type.
1011 // This function takes care of detecting that case and printing the cast
1012 // for the Instruction.
1013 bool CWriter::writeInstructionCast(const Instruction &I) {
1014 bool NeedsExplicitCast = false;
1015 const Type *Ty = I.getOperand(0)->getType();
1016 switch (I.getOpcode()) {
1017 case Instruction::LShr:
1018 case Instruction::URem:
1019 case Instruction::UDiv:
1020 NeedsExplicitCast = Ty->isSigned(); break;
1021 case Instruction::AShr:
1022 case Instruction::SRem:
1023 case Instruction::SDiv:
1024 NeedsExplicitCast = Ty->isUnsigned(); break;
1025 case Instruction::ZExt:
1026 case Instruction::SExt:
1027 case Instruction::Trunc:
1028 case Instruction::FPTrunc:
1029 case Instruction::FPExt:
1030 case Instruction::UIToFP:
1031 case Instruction::SIToFP:
1032 case Instruction::FPToUI:
1033 case Instruction::FPToSI:
1034 case Instruction::PtrToInt:
1035 case Instruction::IntToPtr:
1036 case Instruction::BitCast:
1038 NeedsExplicitCast = true;
1042 if (NeedsExplicitCast) {
1047 return NeedsExplicitCast;
1050 // Write the operand with a cast to another type based on the Opcode being used.
1051 // This will be used in cases where an instruction has specific type
1052 // requirements (usually signedness) for its operands.
1053 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1055 // Extract the operand's type, we'll need it.
1056 const Type* OpTy = Operand->getType();
1058 // Indicate whether to do the cast or not.
1059 bool shouldCast = false;
1061 // Based on the Opcode for which this Operand is being written, determine
1062 // the new type to which the operand should be casted by setting the value
1063 // of OpTy. If we change OpTy, also set shouldCast to true.
1066 // for most instructions, it doesn't matter
1068 case Instruction::LShr:
1069 case Instruction::UDiv:
1070 case Instruction::URem:
1071 // For UDiv to have unsigned operands
1072 if (OpTy->isSigned()) {
1073 OpTy = OpTy->getUnsignedVersion();
1077 case Instruction::AShr:
1078 case Instruction::SDiv:
1079 case Instruction::SRem:
1080 if (OpTy->isUnsigned()) {
1081 OpTy = OpTy->getSignedVersion();
1087 // Write out the casted operand if we should, otherwise just write the
1091 printType(Out, OpTy);
1093 writeOperand(Operand);
1096 writeOperand(Operand);
1100 // generateCompilerSpecificCode - This is where we add conditional compilation
1101 // directives to cater to specific compilers as need be.
1103 static void generateCompilerSpecificCode(std::ostream& Out) {
1104 // Alloca is hard to get, and we don't want to include stdlib.h here.
1105 Out << "/* get a declaration for alloca */\n"
1106 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1107 << "extern void *_alloca(unsigned long);\n"
1108 << "#define alloca(x) _alloca(x)\n"
1109 << "#elif defined(__APPLE__)\n"
1110 << "extern void *__builtin_alloca(unsigned long);\n"
1111 << "#define alloca(x) __builtin_alloca(x)\n"
1112 << "#elif defined(__sun__)\n"
1113 << "#if defined(__sparcv9)\n"
1114 << "extern void *__builtin_alloca(unsigned long);\n"
1116 << "extern void *__builtin_alloca(unsigned int);\n"
1118 << "#define alloca(x) __builtin_alloca(x)\n"
1119 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
1120 << "#define alloca(x) __builtin_alloca(x)\n"
1121 << "#elif !defined(_MSC_VER)\n"
1122 << "#include <alloca.h>\n"
1125 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1126 // If we aren't being compiled with GCC, just drop these attributes.
1127 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1128 << "#define __attribute__(X)\n"
1132 // At some point, we should support "external weak" vs. "weak" linkages.
1133 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1134 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1135 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1136 << "#elif defined(__GNUC__)\n"
1137 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1139 << "#define __EXTERNAL_WEAK__\n"
1143 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1144 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1145 << "#define __ATTRIBUTE_WEAK__\n"
1146 << "#elif defined(__GNUC__)\n"
1147 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1149 << "#define __ATTRIBUTE_WEAK__\n"
1152 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1153 // From the GCC documentation:
1155 // double __builtin_nan (const char *str)
1157 // This is an implementation of the ISO C99 function nan.
1159 // Since ISO C99 defines this function in terms of strtod, which we do
1160 // not implement, a description of the parsing is in order. The string is
1161 // parsed as by strtol; that is, the base is recognized by leading 0 or
1162 // 0x prefixes. The number parsed is placed in the significand such that
1163 // the least significant bit of the number is at the least significant
1164 // bit of the significand. The number is truncated to fit the significand
1165 // field provided. The significand is forced to be a quiet NaN.
1167 // This function, if given a string literal, is evaluated early enough
1168 // that it is considered a compile-time constant.
1170 // float __builtin_nanf (const char *str)
1172 // Similar to __builtin_nan, except the return type is float.
1174 // double __builtin_inf (void)
1176 // Similar to __builtin_huge_val, except a warning is generated if the
1177 // target floating-point format does not support infinities. This
1178 // function is suitable for implementing the ISO C99 macro INFINITY.
1180 // float __builtin_inff (void)
1182 // Similar to __builtin_inf, except the return type is float.
1183 Out << "#ifdef __GNUC__\n"
1184 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1185 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1186 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1187 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1188 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1189 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1190 << "#define LLVM_PREFETCH(addr,rw,locality) "
1191 "__builtin_prefetch(addr,rw,locality)\n"
1192 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1193 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1194 << "#define LLVM_ASM __asm__\n"
1196 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1197 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1198 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1199 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1200 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1201 << "#define LLVM_INFF 0.0F /* Float */\n"
1202 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1203 << "#define __ATTRIBUTE_CTOR__\n"
1204 << "#define __ATTRIBUTE_DTOR__\n"
1205 << "#define LLVM_ASM(X)\n"
1208 // Output target-specific code that should be inserted into main.
1209 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1210 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
1211 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
1212 << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
1213 << "defined(__x86_64__)\n"
1214 << "#undef CODE_FOR_MAIN\n"
1215 << "#define CODE_FOR_MAIN() \\\n"
1216 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
1217 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
1218 << "#endif\n#endif\n";
1222 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1223 /// the StaticTors set.
1224 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1225 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1226 if (!InitList) return;
1228 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1229 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1230 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1232 if (CS->getOperand(1)->isNullValue())
1233 return; // Found a null terminator, exit printing.
1234 Constant *FP = CS->getOperand(1);
1235 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1237 FP = CE->getOperand(0);
1238 if (Function *F = dyn_cast<Function>(FP))
1239 StaticTors.insert(F);
1243 enum SpecialGlobalClass {
1245 GlobalCtors, GlobalDtors,
1249 /// getGlobalVariableClass - If this is a global that is specially recognized
1250 /// by LLVM, return a code that indicates how we should handle it.
1251 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1252 // If this is a global ctors/dtors list, handle it now.
1253 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1254 if (GV->getName() == "llvm.global_ctors")
1256 else if (GV->getName() == "llvm.global_dtors")
1260 // Otherwise, it it is other metadata, don't print it. This catches things
1261 // like debug information.
1262 if (GV->getSection() == "llvm.metadata")
1269 bool CWriter::doInitialization(Module &M) {
1273 IL.AddPrototypes(M);
1275 // Ensure that all structure types have names...
1276 Mang = new Mangler(M);
1277 Mang->markCharUnacceptable('.');
1279 // Keep track of which functions are static ctors/dtors so they can have
1280 // an attribute added to their prototypes.
1281 std::set<Function*> StaticCtors, StaticDtors;
1282 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1284 switch (getGlobalVariableClass(I)) {
1287 FindStaticTors(I, StaticCtors);
1290 FindStaticTors(I, StaticDtors);
1295 // get declaration for alloca
1296 Out << "/* Provide Declarations */\n";
1297 Out << "#include <stdarg.h>\n"; // Varargs support
1298 Out << "#include <setjmp.h>\n"; // Unwind support
1299 generateCompilerSpecificCode(Out);
1301 // Provide a definition for `bool' if not compiling with a C++ compiler.
1303 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1305 << "\n\n/* Support for floating point constants */\n"
1306 << "typedef unsigned long long ConstantDoubleTy;\n"
1307 << "typedef unsigned int ConstantFloatTy;\n"
1309 << "\n\n/* Global Declarations */\n";
1311 // First output all the declarations for the program, because C requires
1312 // Functions & globals to be declared before they are used.
1315 // Loop over the symbol table, emitting all named constants...
1316 printModuleTypes(M.getSymbolTable());
1318 // Global variable declarations...
1319 if (!M.global_empty()) {
1320 Out << "\n/* External Global Variable Declarations */\n";
1321 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1323 if (I->hasExternalLinkage()) {
1325 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1327 } else if (I->hasDLLImportLinkage()) {
1328 Out << "__declspec(dllimport) ";
1329 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1335 // Function declarations
1336 Out << "\n/* Function Declarations */\n";
1337 Out << "double fmod(double, double);\n"; // Support for FP rem
1338 Out << "float fmodf(float, float);\n";
1340 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1341 // Don't print declarations for intrinsic functions.
1342 if (!I->getIntrinsicID() && I->getName() != "setjmp" &&
1343 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1344 printFunctionSignature(I, true);
1345 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1346 Out << " __ATTRIBUTE_WEAK__";
1347 if (StaticCtors.count(I))
1348 Out << " __ATTRIBUTE_CTOR__";
1349 if (StaticDtors.count(I))
1350 Out << " __ATTRIBUTE_DTOR__";
1352 if (I->hasName() && I->getName()[0] == 1)
1353 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1359 // Output the global variable declarations
1360 if (!M.global_empty()) {
1361 Out << "\n\n/* Global Variable Declarations */\n";
1362 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1364 if (!I->isExternal()) {
1365 // Ignore special globals, such as debug info.
1366 if (getGlobalVariableClass(I))
1369 if (I->hasInternalLinkage())
1373 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1375 if (I->hasLinkOnceLinkage())
1376 Out << " __attribute__((common))";
1377 else if (I->hasWeakLinkage())
1378 Out << " __ATTRIBUTE_WEAK__";
1383 // Output the global variable definitions and contents...
1384 if (!M.global_empty()) {
1385 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1386 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1388 if (!I->isExternal()) {
1389 // Ignore special globals, such as debug info.
1390 if (getGlobalVariableClass(I))
1393 if (I->hasInternalLinkage())
1395 else if (I->hasDLLImportLinkage())
1396 Out << "__declspec(dllimport) ";
1397 else if (I->hasDLLExportLinkage())
1398 Out << "__declspec(dllexport) ";
1400 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1401 if (I->hasLinkOnceLinkage())
1402 Out << " __attribute__((common))";
1403 else if (I->hasWeakLinkage())
1404 Out << " __ATTRIBUTE_WEAK__";
1406 // If the initializer is not null, emit the initializer. If it is null,
1407 // we try to avoid emitting large amounts of zeros. The problem with
1408 // this, however, occurs when the variable has weak linkage. In this
1409 // case, the assembler will complain about the variable being both weak
1410 // and common, so we disable this optimization.
1411 if (!I->getInitializer()->isNullValue()) {
1413 writeOperand(I->getInitializer());
1414 } else if (I->hasWeakLinkage()) {
1415 // We have to specify an initializer, but it doesn't have to be
1416 // complete. If the value is an aggregate, print out { 0 }, and let
1417 // the compiler figure out the rest of the zeros.
1419 if (isa<StructType>(I->getInitializer()->getType()) ||
1420 isa<ArrayType>(I->getInitializer()->getType()) ||
1421 isa<PackedType>(I->getInitializer()->getType())) {
1424 // Just print it out normally.
1425 writeOperand(I->getInitializer());
1433 Out << "\n\n/* Function Bodies */\n";
1438 /// Output all floating point constants that cannot be printed accurately...
1439 void CWriter::printFloatingPointConstants(Function &F) {
1440 // Scan the module for floating point constants. If any FP constant is used
1441 // in the function, we want to redirect it here so that we do not depend on
1442 // the precision of the printed form, unless the printed form preserves
1445 static unsigned FPCounter = 0;
1446 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1448 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1449 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1450 !FPConstantMap.count(FPC)) {
1451 double Val = FPC->getValue();
1453 FPConstantMap[FPC] = FPCounter; // Number the FP constants
1455 if (FPC->getType() == Type::DoubleTy) {
1456 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1457 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
1458 << "ULL; /* " << Val << " */\n";
1459 } else if (FPC->getType() == Type::FloatTy) {
1460 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1461 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
1462 << "U; /* " << Val << " */\n";
1464 assert(0 && "Unknown float type!");
1471 /// printSymbolTable - Run through symbol table looking for type names. If a
1472 /// type name is found, emit its declaration...
1474 void CWriter::printModuleTypes(const SymbolTable &ST) {
1475 // We are only interested in the type plane of the symbol table.
1476 SymbolTable::type_const_iterator I = ST.type_begin();
1477 SymbolTable::type_const_iterator End = ST.type_end();
1479 // If there are no type names, exit early.
1480 if (I == End) return;
1482 // Print out forward declarations for structure types before anything else!
1483 Out << "/* Structure forward decls */\n";
1484 for (; I != End; ++I)
1485 if (const Type *STy = dyn_cast<StructType>(I->second)) {
1486 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1487 Out << Name << ";\n";
1488 TypeNames.insert(std::make_pair(STy, Name));
1493 // Now we can print out typedefs...
1494 Out << "/* Typedefs */\n";
1495 for (I = ST.type_begin(); I != End; ++I) {
1496 const Type *Ty = cast<Type>(I->second);
1497 std::string Name = "l_" + Mang->makeNameProper(I->first);
1499 printType(Out, Ty, Name);
1505 // Keep track of which structures have been printed so far...
1506 std::set<const StructType *> StructPrinted;
1508 // Loop over all structures then push them into the stack so they are
1509 // printed in the correct order.
1511 Out << "/* Structure contents */\n";
1512 for (I = ST.type_begin(); I != End; ++I)
1513 if (const StructType *STy = dyn_cast<StructType>(I->second))
1514 // Only print out used types!
1515 printContainedStructs(STy, StructPrinted);
1518 // Push the struct onto the stack and recursively push all structs
1519 // this one depends on.
1521 // TODO: Make this work properly with packed types
1523 void CWriter::printContainedStructs(const Type *Ty,
1524 std::set<const StructType*> &StructPrinted){
1525 // Don't walk through pointers.
1526 if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1528 // Print all contained types first.
1529 for (Type::subtype_iterator I = Ty->subtype_begin(),
1530 E = Ty->subtype_end(); I != E; ++I)
1531 printContainedStructs(*I, StructPrinted);
1533 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1534 // Check to see if we have already printed this struct.
1535 if (StructPrinted.insert(STy).second) {
1536 // Print structure type out.
1537 std::string Name = TypeNames[STy];
1538 printType(Out, STy, Name, true);
1544 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1545 /// isCStructReturn - Should this function actually return a struct by-value?
1546 bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
1548 if (F->hasInternalLinkage()) Out << "static ";
1549 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1550 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
1551 switch (F->getCallingConv()) {
1552 case CallingConv::X86_StdCall:
1553 Out << "__stdcall ";
1555 case CallingConv::X86_FastCall:
1556 Out << "__fastcall ";
1560 // Loop over the arguments, printing them...
1561 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1563 std::stringstream FunctionInnards;
1565 // Print out the name...
1566 FunctionInnards << Mang->getValueName(F) << '(';
1568 bool PrintedArg = false;
1569 if (!F->isExternal()) {
1570 if (!F->arg_empty()) {
1571 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1573 // If this is a struct-return function, don't print the hidden
1574 // struct-return argument.
1575 if (isCStructReturn) {
1576 assert(I != E && "Invalid struct return function!");
1580 std::string ArgName;
1581 for (; I != E; ++I) {
1582 if (PrintedArg) FunctionInnards << ", ";
1583 if (I->hasName() || !Prototype)
1584 ArgName = Mang->getValueName(I);
1587 printType(FunctionInnards, I->getType(), ArgName);
1592 // Loop over the arguments, printing them.
1593 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1595 // If this is a struct-return function, don't print the hidden
1596 // struct-return argument.
1597 if (isCStructReturn) {
1598 assert(I != E && "Invalid struct return function!");
1602 for (; I != E; ++I) {
1603 if (PrintedArg) FunctionInnards << ", ";
1604 printType(FunctionInnards, *I);
1609 // Finish printing arguments... if this is a vararg function, print the ...,
1610 // unless there are no known types, in which case, we just emit ().
1612 if (FT->isVarArg() && PrintedArg) {
1613 if (PrintedArg) FunctionInnards << ", ";
1614 FunctionInnards << "..."; // Output varargs portion of signature!
1615 } else if (!FT->isVarArg() && !PrintedArg) {
1616 FunctionInnards << "void"; // ret() -> ret(void) in C.
1618 FunctionInnards << ')';
1620 // Get the return tpe for the function.
1622 if (!isCStructReturn)
1623 RetTy = F->getReturnType();
1625 // If this is a struct-return function, print the struct-return type.
1626 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1629 // Print out the return type and the signature built above.
1630 printType(Out, RetTy, FunctionInnards.str());
1633 void CWriter::printFunction(Function &F) {
1634 printFunctionSignature(&F, false);
1637 // If this is a struct return function, handle the result with magic.
1638 if (F.getCallingConv() == CallingConv::CSRet) {
1639 const Type *StructTy =
1640 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1642 printType(Out, StructTy, "StructReturn");
1643 Out << "; /* Struct return temporary */\n";
1646 printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
1647 Out << " = &StructReturn;\n";
1650 bool PrintedVar = false;
1652 // print local variable information for the function
1653 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
1654 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1656 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
1657 Out << "; /* Address-exposed local */\n";
1659 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1661 printType(Out, I->getType(), Mang->getValueName(&*I));
1664 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1666 printType(Out, I->getType(),
1667 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
1676 if (F.hasExternalLinkage() && F.getName() == "main")
1677 Out << " CODE_FOR_MAIN();\n";
1679 // print the basic blocks
1680 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1681 if (Loop *L = LI->getLoopFor(BB)) {
1682 if (L->getHeader() == BB && L->getParentLoop() == 0)
1685 printBasicBlock(BB);
1692 void CWriter::printLoop(Loop *L) {
1693 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1694 << "' to make GCC happy */\n";
1695 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1696 BasicBlock *BB = L->getBlocks()[i];
1697 Loop *BBLoop = LI->getLoopFor(BB);
1699 printBasicBlock(BB);
1700 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1703 Out << " } while (1); /* end of syntactic loop '"
1704 << L->getHeader()->getName() << "' */\n";
1707 void CWriter::printBasicBlock(BasicBlock *BB) {
1709 // Don't print the label for the basic block if there are no uses, or if
1710 // the only terminator use is the predecessor basic block's terminator.
1711 // We have to scan the use list because PHI nodes use basic blocks too but
1712 // do not require a label to be generated.
1714 bool NeedsLabel = false;
1715 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1716 if (isGotoCodeNecessary(*PI, BB)) {
1721 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1723 // Output all of the instructions in the basic block...
1724 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1726 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1727 if (II->getType() != Type::VoidTy)
1736 // Don't emit prefix or suffix for the terminator...
1737 visit(*BB->getTerminator());
1741 // Specific Instruction type classes... note that all of the casts are
1742 // necessary because we use the instruction classes as opaque types...
1744 void CWriter::visitReturnInst(ReturnInst &I) {
1745 // If this is a struct return function, return the temporary struct.
1746 if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
1747 Out << " return StructReturn;\n";
1751 // Don't output a void return if this is the last basic block in the function
1752 if (I.getNumOperands() == 0 &&
1753 &*--I.getParent()->getParent()->end() == I.getParent() &&
1754 !I.getParent()->size() == 1) {
1759 if (I.getNumOperands()) {
1761 writeOperand(I.getOperand(0));
1766 void CWriter::visitSwitchInst(SwitchInst &SI) {
1769 writeOperand(SI.getOperand(0));
1770 Out << ") {\n default:\n";
1771 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
1772 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1774 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1776 writeOperand(SI.getOperand(i));
1778 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1779 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
1780 printBranchToBlock(SI.getParent(), Succ, 2);
1781 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
1787 void CWriter::visitUnreachableInst(UnreachableInst &I) {
1788 Out << " /*UNREACHABLE*/;\n";
1791 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1792 /// FIXME: This should be reenabled, but loop reordering safe!!
1795 if (next(Function::iterator(From)) != Function::iterator(To))
1796 return true; // Not the direct successor, we need a goto.
1798 //isa<SwitchInst>(From->getTerminator())
1800 if (LI->getLoopFor(From) != LI->getLoopFor(To))
1805 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
1806 BasicBlock *Successor,
1808 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1809 PHINode *PN = cast<PHINode>(I);
1810 // Now we have to do the printing.
1811 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1812 if (!isa<UndefValue>(IV)) {
1813 Out << std::string(Indent, ' ');
1814 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1816 Out << "; /* for PHI node */\n";
1821 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1823 if (isGotoCodeNecessary(CurBB, Succ)) {
1824 Out << std::string(Indent, ' ') << " goto ";
1830 // Branch instruction printing - Avoid printing out a branch to a basic block
1831 // that immediately succeeds the current one.
1833 void CWriter::visitBranchInst(BranchInst &I) {
1835 if (I.isConditional()) {
1836 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1838 writeOperand(I.getCondition());
1841 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
1842 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1844 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1845 Out << " } else {\n";
1846 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1847 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1850 // First goto not necessary, assume second one is...
1852 writeOperand(I.getCondition());
1855 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1856 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1861 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
1862 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1867 // PHI nodes get copied into temporary values at the end of predecessor basic
1868 // blocks. We now need to copy these temporary values into the REAL value for
1870 void CWriter::visitPHINode(PHINode &I) {
1872 Out << "__PHI_TEMPORARY";
1876 void CWriter::visitBinaryOperator(Instruction &I) {
1877 // binary instructions, shift instructions, setCond instructions.
1878 assert(!isa<PointerType>(I.getType()));
1880 // We must cast the results of binary operations which might be promoted.
1881 bool needsCast = false;
1882 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1883 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1884 || (I.getType() == Type::FloatTy)) {
1887 printType(Out, I.getType());
1891 // If this is a negation operation, print it out as such. For FP, we don't
1892 // want to print "-0.0 - X".
1893 if (BinaryOperator::isNeg(&I)) {
1895 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
1897 } else if (I.getOpcode() == Instruction::FRem) {
1898 // Output a call to fmod/fmodf instead of emitting a%b
1899 if (I.getType() == Type::FloatTy)
1903 writeOperand(I.getOperand(0));
1905 writeOperand(I.getOperand(1));
1909 // Write out the cast of the instruction's value back to the proper type
1911 bool NeedsClosingParens = writeInstructionCast(I);
1913 // Certain instructions require the operand to be forced to a specific type
1914 // so we use writeOperandWithCast here instead of writeOperand. Similarly
1915 // below for operand 1
1916 writeOperandWithCast(I.getOperand(0), I.getOpcode());
1918 switch (I.getOpcode()) {
1919 case Instruction::Add: Out << " + "; break;
1920 case Instruction::Sub: Out << " - "; break;
1921 case Instruction::Mul: Out << '*'; break;
1922 case Instruction::URem:
1923 case Instruction::SRem:
1924 case Instruction::FRem: Out << '%'; break;
1925 case Instruction::UDiv:
1926 case Instruction::SDiv:
1927 case Instruction::FDiv: Out << '/'; break;
1928 case Instruction::And: Out << " & "; break;
1929 case Instruction::Or: Out << " | "; break;
1930 case Instruction::Xor: Out << " ^ "; break;
1931 case Instruction::SetEQ: Out << " == "; break;
1932 case Instruction::SetNE: Out << " != "; break;
1933 case Instruction::SetLE: Out << " <= "; break;
1934 case Instruction::SetGE: Out << " >= "; break;
1935 case Instruction::SetLT: Out << " < "; break;
1936 case Instruction::SetGT: Out << " > "; break;
1937 case Instruction::Shl : Out << " << "; break;
1938 case Instruction::LShr:
1939 case Instruction::AShr: Out << " >> "; break;
1940 default: std::cerr << "Invalid operator type!" << I; abort();
1943 writeOperandWithCast(I.getOperand(1), I.getOpcode());
1944 if (NeedsClosingParens)
1953 void CWriter::visitCastInst(CastInst &I) {
1954 const Type *DstTy = I.getType();
1955 const Type *SrcTy = I.getOperand(0)->getType();
1957 printCast(I.getOpcode(), SrcTy, DstTy);
1958 if (I.getOpcode() == Instruction::SExt && SrcTy == Type::BoolTy) {
1959 // Make sure we really get a sext from bool by subtracing the bool from 0
1962 writeOperand(I.getOperand(0));
1963 if (I.getOpcode() == Instruction::Trunc && DstTy == Type::BoolTy) {
1964 // Make sure we really get a trunc to bool by anding the operand with 1
1970 void CWriter::visitSelectInst(SelectInst &I) {
1972 writeOperand(I.getCondition());
1974 writeOperand(I.getTrueValue());
1976 writeOperand(I.getFalseValue());
1981 void CWriter::lowerIntrinsics(Function &F) {
1982 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1983 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1984 if (CallInst *CI = dyn_cast<CallInst>(I++))
1985 if (Function *F = CI->getCalledFunction())
1986 switch (F->getIntrinsicID()) {
1987 case Intrinsic::not_intrinsic:
1988 case Intrinsic::vastart:
1989 case Intrinsic::vacopy:
1990 case Intrinsic::vaend:
1991 case Intrinsic::returnaddress:
1992 case Intrinsic::frameaddress:
1993 case Intrinsic::setjmp:
1994 case Intrinsic::longjmp:
1995 case Intrinsic::prefetch:
1996 case Intrinsic::dbg_stoppoint:
1997 case Intrinsic::powi_f32:
1998 case Intrinsic::powi_f64:
1999 // We directly implement these intrinsics
2002 // If this is an intrinsic that directly corresponds to a GCC
2003 // builtin, we handle it.
2004 const char *BuiltinName = "";
2005 #define GET_GCC_BUILTIN_NAME
2006 #include "llvm/Intrinsics.gen"
2007 #undef GET_GCC_BUILTIN_NAME
2008 // If we handle it, don't lower it.
2009 if (BuiltinName[0]) break;
2011 // All other intrinsic calls we must lower.
2012 Instruction *Before = 0;
2013 if (CI != &BB->front())
2014 Before = prior(BasicBlock::iterator(CI));
2016 IL.LowerIntrinsicCall(CI);
2017 if (Before) { // Move iterator to instruction after call
2028 void CWriter::visitCallInst(CallInst &I) {
2029 bool WroteCallee = false;
2031 // Handle intrinsic function calls first...
2032 if (Function *F = I.getCalledFunction())
2033 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
2036 // If this is an intrinsic that directly corresponds to a GCC
2037 // builtin, we emit it here.
2038 const char *BuiltinName = "";
2039 #define GET_GCC_BUILTIN_NAME
2040 #include "llvm/Intrinsics.gen"
2041 #undef GET_GCC_BUILTIN_NAME
2042 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2048 case Intrinsic::vastart:
2051 Out << "va_start(*(va_list*)";
2052 writeOperand(I.getOperand(1));
2054 // Output the last argument to the enclosing function...
2055 if (I.getParent()->getParent()->arg_empty()) {
2056 std::cerr << "The C backend does not currently support zero "
2057 << "argument varargs functions, such as '"
2058 << I.getParent()->getParent()->getName() << "'!\n";
2061 writeOperand(--I.getParent()->getParent()->arg_end());
2064 case Intrinsic::vaend:
2065 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2066 Out << "0; va_end(*(va_list*)";
2067 writeOperand(I.getOperand(1));
2070 Out << "va_end(*(va_list*)0)";
2073 case Intrinsic::vacopy:
2075 Out << "va_copy(*(va_list*)";
2076 writeOperand(I.getOperand(1));
2077 Out << ", *(va_list*)";
2078 writeOperand(I.getOperand(2));
2081 case Intrinsic::returnaddress:
2082 Out << "__builtin_return_address(";
2083 writeOperand(I.getOperand(1));
2086 case Intrinsic::frameaddress:
2087 Out << "__builtin_frame_address(";
2088 writeOperand(I.getOperand(1));
2091 case Intrinsic::powi_f32:
2092 case Intrinsic::powi_f64:
2093 Out << "__builtin_powi(";
2094 writeOperand(I.getOperand(1));
2096 writeOperand(I.getOperand(2));
2099 case Intrinsic::setjmp:
2100 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
2101 Out << "_"; // Use _setjmp on systems that support it!
2103 Out << "setjmp(*(jmp_buf*)";
2104 writeOperand(I.getOperand(1));
2107 case Intrinsic::longjmp:
2108 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
2109 Out << "_"; // Use _longjmp on systems that support it!
2111 Out << "longjmp(*(jmp_buf*)";
2112 writeOperand(I.getOperand(1));
2114 writeOperand(I.getOperand(2));
2117 case Intrinsic::prefetch:
2118 Out << "LLVM_PREFETCH((const void *)";
2119 writeOperand(I.getOperand(1));
2121 writeOperand(I.getOperand(2));
2123 writeOperand(I.getOperand(3));
2126 case Intrinsic::dbg_stoppoint: {
2127 // If we use writeOperand directly we get a "u" suffix which is rejected
2129 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2133 << " \"" << SPI.getDirectory()
2134 << SPI.getFileName() << "\"\n";
2140 Value *Callee = I.getCalledValue();
2142 // If this is a call to a struct-return function, assign to the first
2143 // parameter instead of passing it to the call.
2144 bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
2147 writeOperand(I.getOperand(1));
2151 if (I.isTailCall()) Out << " /*tail*/ ";
2153 const PointerType *PTy = cast<PointerType>(Callee->getType());
2154 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2157 // If this is an indirect call to a struct return function, we need to cast
2159 bool NeedsCast = isStructRet && !isa<Function>(Callee);
2161 // GCC is a real PITA. It does not permit codegening casts of functions to
2162 // function pointers if they are in a call (it generates a trap instruction
2163 // instead!). We work around this by inserting a cast to void* in between
2164 // the function and the function pointer cast. Unfortunately, we can't just
2165 // form the constant expression here, because the folder will immediately
2168 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2169 // that void* and function pointers have the same size. :( To deal with this
2170 // in the common case, we handle casts where the number of arguments passed
2173 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2175 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2181 // Ok, just cast the pointer type.
2184 printType(Out, I.getCalledValue()->getType());
2186 printStructReturnPointerFunctionType(Out,
2187 cast<PointerType>(I.getCalledValue()->getType()));
2190 writeOperand(Callee);
2191 if (NeedsCast) Out << ')';
2196 unsigned NumDeclaredParams = FTy->getNumParams();
2198 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2200 if (isStructRet) { // Skip struct return argument.
2205 bool PrintedArg = false;
2206 for (; AI != AE; ++AI, ++ArgNo) {
2207 if (PrintedArg) Out << ", ";
2208 if (ArgNo < NumDeclaredParams &&
2209 (*AI)->getType() != FTy->getParamType(ArgNo)) {
2211 printType(Out, FTy->getParamType(ArgNo));
2220 void CWriter::visitMallocInst(MallocInst &I) {
2221 assert(0 && "lowerallocations pass didn't work!");
2224 void CWriter::visitAllocaInst(AllocaInst &I) {
2226 printType(Out, I.getType());
2227 Out << ") alloca(sizeof(";
2228 printType(Out, I.getType()->getElementType());
2230 if (I.isArrayAllocation()) {
2232 writeOperand(I.getOperand(0));
2237 void CWriter::visitFreeInst(FreeInst &I) {
2238 assert(0 && "lowerallocations pass didn't work!");
2241 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2242 gep_type_iterator E) {
2243 bool HasImplicitAddress = false;
2244 // If accessing a global value with no indexing, avoid *(&GV) syndrome
2245 if (isa<GlobalValue>(Ptr)) {
2246 HasImplicitAddress = true;
2247 } else if (isDirectAlloca(Ptr)) {
2248 HasImplicitAddress = true;
2252 if (!HasImplicitAddress)
2253 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
2255 writeOperandInternal(Ptr);
2259 const Constant *CI = dyn_cast<Constant>(I.getOperand());
2260 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2263 writeOperandInternal(Ptr);
2265 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
2267 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
2270 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
2271 "Can only have implicit address with direct accessing");
2273 if (HasImplicitAddress) {
2275 } else if (CI && CI->isNullValue()) {
2276 gep_type_iterator TmpI = I; ++TmpI;
2278 // Print out the -> operator if possible...
2279 if (TmpI != E && isa<StructType>(*TmpI)) {
2280 Out << (HasImplicitAddress ? "." : "->");
2281 Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
2287 if (isa<StructType>(*I)) {
2288 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
2291 writeOperand(I.getOperand());
2296 void CWriter::visitLoadInst(LoadInst &I) {
2298 if (I.isVolatile()) {
2300 printType(Out, I.getType(), "volatile*");
2304 writeOperand(I.getOperand(0));
2310 void CWriter::visitStoreInst(StoreInst &I) {
2312 if (I.isVolatile()) {
2314 printType(Out, I.getOperand(0)->getType(), " volatile*");
2317 writeOperand(I.getPointerOperand());
2318 if (I.isVolatile()) Out << ')';
2320 writeOperand(I.getOperand(0));
2323 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
2325 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2329 void CWriter::visitVAArgInst(VAArgInst &I) {
2330 Out << "va_arg(*(va_list*)";
2331 writeOperand(I.getOperand(0));
2333 printType(Out, I.getType());
2337 //===----------------------------------------------------------------------===//
2338 // External Interface declaration
2339 //===----------------------------------------------------------------------===//
2341 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2343 CodeGenFileType FileType,
2345 if (FileType != TargetMachine::AssemblyFile) return true;
2347 PM.add(createLowerGCPass());
2348 PM.add(createLowerAllocationsPass(true));
2349 PM.add(createLowerInvokePass());
2350 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
2351 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
2352 PM.add(new CWriter(o));