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->getType() == Type::BoolTy &&
630 (CE->getOpcode() == Instruction::Trunc ||
631 CE->getOpcode() == Instruction::FPToUI ||
632 CE->getOpcode() == Instruction::FPToSI ||
633 CE->getOpcode() == Instruction::PtrToInt)) {
634 // Make sure we really truncate to bool here by anding with 1
640 case Instruction::GetElementPtr:
642 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
646 case Instruction::Select:
648 printConstant(CE->getOperand(0));
650 printConstant(CE->getOperand(1));
652 printConstant(CE->getOperand(2));
655 case Instruction::Add:
656 case Instruction::Sub:
657 case Instruction::Mul:
658 case Instruction::SDiv:
659 case Instruction::UDiv:
660 case Instruction::FDiv:
661 case Instruction::URem:
662 case Instruction::SRem:
663 case Instruction::FRem:
664 case Instruction::And:
665 case Instruction::Or:
666 case Instruction::Xor:
667 case Instruction::SetEQ:
668 case Instruction::SetNE:
669 case Instruction::SetLT:
670 case Instruction::SetLE:
671 case Instruction::SetGT:
672 case Instruction::SetGE:
673 case Instruction::Shl:
674 case Instruction::LShr:
675 case Instruction::AShr:
678 bool NeedsClosingParens = printConstExprCast(CE);
679 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
680 switch (CE->getOpcode()) {
681 case Instruction::Add: Out << " + "; break;
682 case Instruction::Sub: Out << " - "; break;
683 case Instruction::Mul: Out << " * "; break;
684 case Instruction::URem:
685 case Instruction::SRem:
686 case Instruction::FRem: Out << " % "; break;
687 case Instruction::UDiv:
688 case Instruction::SDiv:
689 case Instruction::FDiv: Out << " / "; break;
690 case Instruction::And: Out << " & "; break;
691 case Instruction::Or: Out << " | "; break;
692 case Instruction::Xor: Out << " ^ "; break;
693 case Instruction::SetEQ: Out << " == "; break;
694 case Instruction::SetNE: Out << " != "; break;
695 case Instruction::SetLT: Out << " < "; break;
696 case Instruction::SetLE: Out << " <= "; break;
697 case Instruction::SetGT: Out << " > "; break;
698 case Instruction::SetGE: Out << " >= "; break;
699 case Instruction::Shl: Out << " << "; break;
700 case Instruction::LShr:
701 case Instruction::AShr: Out << " >> "; break;
702 default: assert(0 && "Illegal opcode here!");
704 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
705 if (NeedsClosingParens)
712 std::cerr << "CWriter Error: Unhandled constant expression: "
716 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
718 printType(Out, CPV->getType());
719 Out << ")/*UNDEF*/0)";
723 switch (CPV->getType()->getTypeID()) {
725 Out << (cast<ConstantBool>(CPV)->getValue() ? '1' : '0');
727 case Type::SByteTyID:
728 case Type::ShortTyID:
729 Out << cast<ConstantInt>(CPV)->getSExtValue();
732 if ((int)cast<ConstantInt>(CPV)->getSExtValue() == (int)0x80000000)
733 Out << "((int)0x80000000U)"; // Handle MININT specially to avoid warning
735 Out << cast<ConstantInt>(CPV)->getSExtValue();
739 if (cast<ConstantInt>(CPV)->isMinValue())
740 Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
742 Out << cast<ConstantInt>(CPV)->getSExtValue() << "ll";
745 case Type::UByteTyID:
746 case Type::UShortTyID:
747 Out << cast<ConstantInt>(CPV)->getZExtValue();
750 Out << cast<ConstantInt>(CPV)->getZExtValue() << 'u';
752 case Type::ULongTyID:
753 Out << cast<ConstantInt>(CPV)->getZExtValue() << "ull";
756 case Type::FloatTyID:
757 case Type::DoubleTyID: {
758 ConstantFP *FPC = cast<ConstantFP>(CPV);
759 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
760 if (I != FPConstantMap.end()) {
761 // Because of FP precision problems we must load from a stack allocated
762 // value that holds the value in hex.
763 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
764 << "*)&FPConstant" << I->second << ')';
766 if (IsNAN(FPC->getValue())) {
769 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
771 const unsigned long QuietNaN = 0x7ff8UL;
772 //const unsigned long SignalNaN = 0x7ff4UL;
774 // We need to grab the first part of the FP #
777 uint64_t ll = DoubleToBits(FPC->getValue());
778 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
780 std::string Num(&Buffer[0], &Buffer[6]);
781 unsigned long Val = strtoul(Num.c_str(), 0, 16);
783 if (FPC->getType() == Type::FloatTy)
784 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
785 << Buffer << "\") /*nan*/ ";
787 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
788 << Buffer << "\") /*nan*/ ";
789 } else if (IsInf(FPC->getValue())) {
791 if (FPC->getValue() < 0) Out << '-';
792 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
796 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
797 // Print out the constant as a floating point number.
799 sprintf(Buffer, "%a", FPC->getValue());
802 Num = ftostr(FPC->getValue());
810 case Type::ArrayTyID:
811 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
812 const ArrayType *AT = cast<ArrayType>(CPV->getType());
814 if (AT->getNumElements()) {
816 Constant *CZ = Constant::getNullValue(AT->getElementType());
818 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
825 printConstantArray(cast<ConstantArray>(CPV));
829 case Type::PackedTyID:
830 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
831 const PackedType *AT = cast<PackedType>(CPV->getType());
833 if (AT->getNumElements()) {
835 Constant *CZ = Constant::getNullValue(AT->getElementType());
837 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
844 printConstantPacked(cast<ConstantPacked>(CPV));
848 case Type::StructTyID:
849 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
850 const StructType *ST = cast<StructType>(CPV->getType());
852 if (ST->getNumElements()) {
854 printConstant(Constant::getNullValue(ST->getElementType(0)));
855 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
857 printConstant(Constant::getNullValue(ST->getElementType(i)));
863 if (CPV->getNumOperands()) {
865 printConstant(cast<Constant>(CPV->getOperand(0)));
866 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
868 printConstant(cast<Constant>(CPV->getOperand(i)));
875 case Type::PointerTyID:
876 if (isa<ConstantPointerNull>(CPV)) {
878 printType(Out, CPV->getType());
879 Out << ")/*NULL*/0)";
881 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
887 std::cerr << "Unknown constant type: " << *CPV << "\n";
892 // Some constant expressions need to be casted back to the original types
893 // because their operands were casted to the expected type. This function takes
894 // care of detecting that case and printing the cast for the ConstantExpr.
895 bool CWriter::printConstExprCast(const ConstantExpr* CE) {
896 bool NeedsExplicitCast = false;
897 const Type *Ty = CE->getOperand(0)->getType();
898 switch (CE->getOpcode()) {
899 case Instruction::LShr:
900 case Instruction::URem:
901 case Instruction::UDiv:
902 NeedsExplicitCast = Ty->isSigned(); break;
903 case Instruction::AShr:
904 case Instruction::SRem:
905 case Instruction::SDiv:
906 NeedsExplicitCast = Ty->isUnsigned(); break;
907 case Instruction::ZExt:
908 case Instruction::SExt:
909 case Instruction::Trunc:
910 case Instruction::FPTrunc:
911 case Instruction::FPExt:
912 case Instruction::UIToFP:
913 case Instruction::SIToFP:
914 case Instruction::FPToUI:
915 case Instruction::FPToSI:
916 case Instruction::PtrToInt:
917 case Instruction::IntToPtr:
918 case Instruction::BitCast:
920 NeedsExplicitCast = true;
924 if (NeedsExplicitCast) {
929 return NeedsExplicitCast;
932 // Print a constant assuming that it is the operand for a given Opcode. The
933 // opcodes that care about sign need to cast their operands to the expected
934 // type before the operation proceeds. This function does the casting.
935 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
937 // Extract the operand's type, we'll need it.
938 const Type* OpTy = CPV->getType();
940 // Indicate whether to do the cast or not.
941 bool shouldCast = false;
943 // Based on the Opcode for which this Constant is being written, determine
944 // the new type to which the operand should be casted by setting the value
945 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
949 // for most instructions, it doesn't matter
951 case Instruction::LShr:
952 case Instruction::UDiv:
953 case Instruction::URem:
954 // For UDiv/URem get correct type
955 if (OpTy->isSigned()) {
956 OpTy = OpTy->getUnsignedVersion();
960 case Instruction::AShr:
961 case Instruction::SDiv:
962 case Instruction::SRem:
963 // For SDiv/SRem get correct type
964 if (OpTy->isUnsigned()) {
965 OpTy = OpTy->getSignedVersion();
971 // Write out the casted constant if we should, otherwise just write the
975 printType(Out, OpTy);
984 void CWriter::writeOperandInternal(Value *Operand) {
985 if (Instruction *I = dyn_cast<Instruction>(Operand))
986 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
987 // Should we inline this instruction to build a tree?
994 Constant* CPV = dyn_cast<Constant>(Operand);
995 if (CPV && !isa<GlobalValue>(CPV)) {
998 Out << Mang->getValueName(Operand);
1002 void CWriter::writeOperand(Value *Operand) {
1003 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1004 Out << "(&"; // Global variables are referenced as their addresses by llvm
1006 writeOperandInternal(Operand);
1008 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1012 // Some instructions need to have their result value casted back to the
1013 // original types because their operands were casted to the expected type.
1014 // This function takes care of detecting that case and printing the cast
1015 // for the Instruction.
1016 bool CWriter::writeInstructionCast(const Instruction &I) {
1017 bool NeedsExplicitCast = false;
1018 const Type *Ty = I.getOperand(0)->getType();
1019 switch (I.getOpcode()) {
1020 case Instruction::LShr:
1021 case Instruction::URem:
1022 case Instruction::UDiv:
1023 NeedsExplicitCast = Ty->isSigned(); break;
1024 case Instruction::AShr:
1025 case Instruction::SRem:
1026 case Instruction::SDiv:
1027 NeedsExplicitCast = Ty->isUnsigned(); break;
1028 case Instruction::ZExt:
1029 case Instruction::SExt:
1030 case Instruction::Trunc:
1031 case Instruction::FPTrunc:
1032 case Instruction::FPExt:
1033 case Instruction::UIToFP:
1034 case Instruction::SIToFP:
1035 case Instruction::FPToUI:
1036 case Instruction::FPToSI:
1037 case Instruction::PtrToInt:
1038 case Instruction::IntToPtr:
1039 case Instruction::BitCast:
1041 NeedsExplicitCast = true;
1045 if (NeedsExplicitCast) {
1050 return NeedsExplicitCast;
1053 // Write the operand with a cast to another type based on the Opcode being used.
1054 // This will be used in cases where an instruction has specific type
1055 // requirements (usually signedness) for its operands.
1056 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1058 // Extract the operand's type, we'll need it.
1059 const Type* OpTy = Operand->getType();
1061 // Indicate whether to do the cast or not.
1062 bool shouldCast = false;
1064 // Based on the Opcode for which this Operand is being written, determine
1065 // the new type to which the operand should be casted by setting the value
1066 // of OpTy. If we change OpTy, also set shouldCast to true.
1069 // for most instructions, it doesn't matter
1071 case Instruction::LShr:
1072 case Instruction::UDiv:
1073 case Instruction::URem:
1074 // For UDiv to have unsigned operands
1075 if (OpTy->isSigned()) {
1076 OpTy = OpTy->getUnsignedVersion();
1080 case Instruction::AShr:
1081 case Instruction::SDiv:
1082 case Instruction::SRem:
1083 if (OpTy->isUnsigned()) {
1084 OpTy = OpTy->getSignedVersion();
1090 // Write out the casted operand if we should, otherwise just write the
1094 printType(Out, OpTy);
1096 writeOperand(Operand);
1099 writeOperand(Operand);
1103 // generateCompilerSpecificCode - This is where we add conditional compilation
1104 // directives to cater to specific compilers as need be.
1106 static void generateCompilerSpecificCode(std::ostream& Out) {
1107 // Alloca is hard to get, and we don't want to include stdlib.h here.
1108 Out << "/* get a declaration for alloca */\n"
1109 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1110 << "extern void *_alloca(unsigned long);\n"
1111 << "#define alloca(x) _alloca(x)\n"
1112 << "#elif defined(__APPLE__)\n"
1113 << "extern void *__builtin_alloca(unsigned long);\n"
1114 << "#define alloca(x) __builtin_alloca(x)\n"
1115 << "#elif defined(__sun__)\n"
1116 << "#if defined(__sparcv9)\n"
1117 << "extern void *__builtin_alloca(unsigned long);\n"
1119 << "extern void *__builtin_alloca(unsigned int);\n"
1121 << "#define alloca(x) __builtin_alloca(x)\n"
1122 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
1123 << "#define alloca(x) __builtin_alloca(x)\n"
1124 << "#elif !defined(_MSC_VER)\n"
1125 << "#include <alloca.h>\n"
1128 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1129 // If we aren't being compiled with GCC, just drop these attributes.
1130 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1131 << "#define __attribute__(X)\n"
1135 // At some point, we should support "external weak" vs. "weak" linkages.
1136 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1137 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1138 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1139 << "#elif defined(__GNUC__)\n"
1140 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1142 << "#define __EXTERNAL_WEAK__\n"
1146 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1147 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1148 << "#define __ATTRIBUTE_WEAK__\n"
1149 << "#elif defined(__GNUC__)\n"
1150 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1152 << "#define __ATTRIBUTE_WEAK__\n"
1155 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1156 // From the GCC documentation:
1158 // double __builtin_nan (const char *str)
1160 // This is an implementation of the ISO C99 function nan.
1162 // Since ISO C99 defines this function in terms of strtod, which we do
1163 // not implement, a description of the parsing is in order. The string is
1164 // parsed as by strtol; that is, the base is recognized by leading 0 or
1165 // 0x prefixes. The number parsed is placed in the significand such that
1166 // the least significant bit of the number is at the least significant
1167 // bit of the significand. The number is truncated to fit the significand
1168 // field provided. The significand is forced to be a quiet NaN.
1170 // This function, if given a string literal, is evaluated early enough
1171 // that it is considered a compile-time constant.
1173 // float __builtin_nanf (const char *str)
1175 // Similar to __builtin_nan, except the return type is float.
1177 // double __builtin_inf (void)
1179 // Similar to __builtin_huge_val, except a warning is generated if the
1180 // target floating-point format does not support infinities. This
1181 // function is suitable for implementing the ISO C99 macro INFINITY.
1183 // float __builtin_inff (void)
1185 // Similar to __builtin_inf, except the return type is float.
1186 Out << "#ifdef __GNUC__\n"
1187 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1188 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1189 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1190 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1191 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1192 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1193 << "#define LLVM_PREFETCH(addr,rw,locality) "
1194 "__builtin_prefetch(addr,rw,locality)\n"
1195 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1196 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1197 << "#define LLVM_ASM __asm__\n"
1199 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1200 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1201 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1202 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1203 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1204 << "#define LLVM_INFF 0.0F /* Float */\n"
1205 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1206 << "#define __ATTRIBUTE_CTOR__\n"
1207 << "#define __ATTRIBUTE_DTOR__\n"
1208 << "#define LLVM_ASM(X)\n"
1211 // Output target-specific code that should be inserted into main.
1212 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1213 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
1214 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
1215 << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
1216 << "defined(__x86_64__)\n"
1217 << "#undef CODE_FOR_MAIN\n"
1218 << "#define CODE_FOR_MAIN() \\\n"
1219 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
1220 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
1221 << "#endif\n#endif\n";
1225 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1226 /// the StaticTors set.
1227 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1228 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1229 if (!InitList) return;
1231 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1232 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1233 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1235 if (CS->getOperand(1)->isNullValue())
1236 return; // Found a null terminator, exit printing.
1237 Constant *FP = CS->getOperand(1);
1238 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1240 FP = CE->getOperand(0);
1241 if (Function *F = dyn_cast<Function>(FP))
1242 StaticTors.insert(F);
1246 enum SpecialGlobalClass {
1248 GlobalCtors, GlobalDtors,
1252 /// getGlobalVariableClass - If this is a global that is specially recognized
1253 /// by LLVM, return a code that indicates how we should handle it.
1254 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1255 // If this is a global ctors/dtors list, handle it now.
1256 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1257 if (GV->getName() == "llvm.global_ctors")
1259 else if (GV->getName() == "llvm.global_dtors")
1263 // Otherwise, it it is other metadata, don't print it. This catches things
1264 // like debug information.
1265 if (GV->getSection() == "llvm.metadata")
1272 bool CWriter::doInitialization(Module &M) {
1276 IL.AddPrototypes(M);
1278 // Ensure that all structure types have names...
1279 Mang = new Mangler(M);
1280 Mang->markCharUnacceptable('.');
1282 // Keep track of which functions are static ctors/dtors so they can have
1283 // an attribute added to their prototypes.
1284 std::set<Function*> StaticCtors, StaticDtors;
1285 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1287 switch (getGlobalVariableClass(I)) {
1290 FindStaticTors(I, StaticCtors);
1293 FindStaticTors(I, StaticDtors);
1298 // get declaration for alloca
1299 Out << "/* Provide Declarations */\n";
1300 Out << "#include <stdarg.h>\n"; // Varargs support
1301 Out << "#include <setjmp.h>\n"; // Unwind support
1302 generateCompilerSpecificCode(Out);
1304 // Provide a definition for `bool' if not compiling with a C++ compiler.
1306 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1308 << "\n\n/* Support for floating point constants */\n"
1309 << "typedef unsigned long long ConstantDoubleTy;\n"
1310 << "typedef unsigned int ConstantFloatTy;\n"
1312 << "\n\n/* Global Declarations */\n";
1314 // First output all the declarations for the program, because C requires
1315 // Functions & globals to be declared before they are used.
1318 // Loop over the symbol table, emitting all named constants...
1319 printModuleTypes(M.getSymbolTable());
1321 // Global variable declarations...
1322 if (!M.global_empty()) {
1323 Out << "\n/* External Global Variable Declarations */\n";
1324 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1326 if (I->hasExternalLinkage()) {
1328 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1330 } else if (I->hasDLLImportLinkage()) {
1331 Out << "__declspec(dllimport) ";
1332 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1338 // Function declarations
1339 Out << "\n/* Function Declarations */\n";
1340 Out << "double fmod(double, double);\n"; // Support for FP rem
1341 Out << "float fmodf(float, float);\n";
1343 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1344 // Don't print declarations for intrinsic functions.
1345 if (!I->getIntrinsicID() && I->getName() != "setjmp" &&
1346 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1347 printFunctionSignature(I, true);
1348 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1349 Out << " __ATTRIBUTE_WEAK__";
1350 if (StaticCtors.count(I))
1351 Out << " __ATTRIBUTE_CTOR__";
1352 if (StaticDtors.count(I))
1353 Out << " __ATTRIBUTE_DTOR__";
1355 if (I->hasName() && I->getName()[0] == 1)
1356 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1362 // Output the global variable declarations
1363 if (!M.global_empty()) {
1364 Out << "\n\n/* Global Variable Declarations */\n";
1365 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1367 if (!I->isExternal()) {
1368 // Ignore special globals, such as debug info.
1369 if (getGlobalVariableClass(I))
1372 if (I->hasInternalLinkage())
1376 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1378 if (I->hasLinkOnceLinkage())
1379 Out << " __attribute__((common))";
1380 else if (I->hasWeakLinkage())
1381 Out << " __ATTRIBUTE_WEAK__";
1386 // Output the global variable definitions and contents...
1387 if (!M.global_empty()) {
1388 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1389 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1391 if (!I->isExternal()) {
1392 // Ignore special globals, such as debug info.
1393 if (getGlobalVariableClass(I))
1396 if (I->hasInternalLinkage())
1398 else if (I->hasDLLImportLinkage())
1399 Out << "__declspec(dllimport) ";
1400 else if (I->hasDLLExportLinkage())
1401 Out << "__declspec(dllexport) ";
1403 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1404 if (I->hasLinkOnceLinkage())
1405 Out << " __attribute__((common))";
1406 else if (I->hasWeakLinkage())
1407 Out << " __ATTRIBUTE_WEAK__";
1409 // If the initializer is not null, emit the initializer. If it is null,
1410 // we try to avoid emitting large amounts of zeros. The problem with
1411 // this, however, occurs when the variable has weak linkage. In this
1412 // case, the assembler will complain about the variable being both weak
1413 // and common, so we disable this optimization.
1414 if (!I->getInitializer()->isNullValue()) {
1416 writeOperand(I->getInitializer());
1417 } else if (I->hasWeakLinkage()) {
1418 // We have to specify an initializer, but it doesn't have to be
1419 // complete. If the value is an aggregate, print out { 0 }, and let
1420 // the compiler figure out the rest of the zeros.
1422 if (isa<StructType>(I->getInitializer()->getType()) ||
1423 isa<ArrayType>(I->getInitializer()->getType()) ||
1424 isa<PackedType>(I->getInitializer()->getType())) {
1427 // Just print it out normally.
1428 writeOperand(I->getInitializer());
1436 Out << "\n\n/* Function Bodies */\n";
1441 /// Output all floating point constants that cannot be printed accurately...
1442 void CWriter::printFloatingPointConstants(Function &F) {
1443 // Scan the module for floating point constants. If any FP constant is used
1444 // in the function, we want to redirect it here so that we do not depend on
1445 // the precision of the printed form, unless the printed form preserves
1448 static unsigned FPCounter = 0;
1449 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1451 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1452 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1453 !FPConstantMap.count(FPC)) {
1454 double Val = FPC->getValue();
1456 FPConstantMap[FPC] = FPCounter; // Number the FP constants
1458 if (FPC->getType() == Type::DoubleTy) {
1459 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1460 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
1461 << "ULL; /* " << Val << " */\n";
1462 } else if (FPC->getType() == Type::FloatTy) {
1463 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1464 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
1465 << "U; /* " << Val << " */\n";
1467 assert(0 && "Unknown float type!");
1474 /// printSymbolTable - Run through symbol table looking for type names. If a
1475 /// type name is found, emit its declaration...
1477 void CWriter::printModuleTypes(const SymbolTable &ST) {
1478 // We are only interested in the type plane of the symbol table.
1479 SymbolTable::type_const_iterator I = ST.type_begin();
1480 SymbolTable::type_const_iterator End = ST.type_end();
1482 // If there are no type names, exit early.
1483 if (I == End) return;
1485 // Print out forward declarations for structure types before anything else!
1486 Out << "/* Structure forward decls */\n";
1487 for (; I != End; ++I)
1488 if (const Type *STy = dyn_cast<StructType>(I->second)) {
1489 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1490 Out << Name << ";\n";
1491 TypeNames.insert(std::make_pair(STy, Name));
1496 // Now we can print out typedefs...
1497 Out << "/* Typedefs */\n";
1498 for (I = ST.type_begin(); I != End; ++I) {
1499 const Type *Ty = cast<Type>(I->second);
1500 std::string Name = "l_" + Mang->makeNameProper(I->first);
1502 printType(Out, Ty, Name);
1508 // Keep track of which structures have been printed so far...
1509 std::set<const StructType *> StructPrinted;
1511 // Loop over all structures then push them into the stack so they are
1512 // printed in the correct order.
1514 Out << "/* Structure contents */\n";
1515 for (I = ST.type_begin(); I != End; ++I)
1516 if (const StructType *STy = dyn_cast<StructType>(I->second))
1517 // Only print out used types!
1518 printContainedStructs(STy, StructPrinted);
1521 // Push the struct onto the stack and recursively push all structs
1522 // this one depends on.
1524 // TODO: Make this work properly with packed types
1526 void CWriter::printContainedStructs(const Type *Ty,
1527 std::set<const StructType*> &StructPrinted){
1528 // Don't walk through pointers.
1529 if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1531 // Print all contained types first.
1532 for (Type::subtype_iterator I = Ty->subtype_begin(),
1533 E = Ty->subtype_end(); I != E; ++I)
1534 printContainedStructs(*I, StructPrinted);
1536 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1537 // Check to see if we have already printed this struct.
1538 if (StructPrinted.insert(STy).second) {
1539 // Print structure type out.
1540 std::string Name = TypeNames[STy];
1541 printType(Out, STy, Name, true);
1547 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1548 /// isCStructReturn - Should this function actually return a struct by-value?
1549 bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
1551 if (F->hasInternalLinkage()) Out << "static ";
1552 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1553 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
1554 switch (F->getCallingConv()) {
1555 case CallingConv::X86_StdCall:
1556 Out << "__stdcall ";
1558 case CallingConv::X86_FastCall:
1559 Out << "__fastcall ";
1563 // Loop over the arguments, printing them...
1564 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1566 std::stringstream FunctionInnards;
1568 // Print out the name...
1569 FunctionInnards << Mang->getValueName(F) << '(';
1571 bool PrintedArg = false;
1572 if (!F->isExternal()) {
1573 if (!F->arg_empty()) {
1574 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1576 // If this is a struct-return function, don't print the hidden
1577 // struct-return argument.
1578 if (isCStructReturn) {
1579 assert(I != E && "Invalid struct return function!");
1583 std::string ArgName;
1584 for (; I != E; ++I) {
1585 if (PrintedArg) FunctionInnards << ", ";
1586 if (I->hasName() || !Prototype)
1587 ArgName = Mang->getValueName(I);
1590 printType(FunctionInnards, I->getType(), ArgName);
1595 // Loop over the arguments, printing them.
1596 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1598 // If this is a struct-return function, don't print the hidden
1599 // struct-return argument.
1600 if (isCStructReturn) {
1601 assert(I != E && "Invalid struct return function!");
1605 for (; I != E; ++I) {
1606 if (PrintedArg) FunctionInnards << ", ";
1607 printType(FunctionInnards, *I);
1612 // Finish printing arguments... if this is a vararg function, print the ...,
1613 // unless there are no known types, in which case, we just emit ().
1615 if (FT->isVarArg() && PrintedArg) {
1616 if (PrintedArg) FunctionInnards << ", ";
1617 FunctionInnards << "..."; // Output varargs portion of signature!
1618 } else if (!FT->isVarArg() && !PrintedArg) {
1619 FunctionInnards << "void"; // ret() -> ret(void) in C.
1621 FunctionInnards << ')';
1623 // Get the return tpe for the function.
1625 if (!isCStructReturn)
1626 RetTy = F->getReturnType();
1628 // If this is a struct-return function, print the struct-return type.
1629 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1632 // Print out the return type and the signature built above.
1633 printType(Out, RetTy, FunctionInnards.str());
1636 void CWriter::printFunction(Function &F) {
1637 printFunctionSignature(&F, false);
1640 // If this is a struct return function, handle the result with magic.
1641 if (F.getCallingConv() == CallingConv::CSRet) {
1642 const Type *StructTy =
1643 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1645 printType(Out, StructTy, "StructReturn");
1646 Out << "; /* Struct return temporary */\n";
1649 printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
1650 Out << " = &StructReturn;\n";
1653 bool PrintedVar = false;
1655 // print local variable information for the function
1656 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
1657 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1659 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
1660 Out << "; /* Address-exposed local */\n";
1662 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1664 printType(Out, I->getType(), Mang->getValueName(&*I));
1667 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1669 printType(Out, I->getType(),
1670 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
1679 if (F.hasExternalLinkage() && F.getName() == "main")
1680 Out << " CODE_FOR_MAIN();\n";
1682 // print the basic blocks
1683 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1684 if (Loop *L = LI->getLoopFor(BB)) {
1685 if (L->getHeader() == BB && L->getParentLoop() == 0)
1688 printBasicBlock(BB);
1695 void CWriter::printLoop(Loop *L) {
1696 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1697 << "' to make GCC happy */\n";
1698 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1699 BasicBlock *BB = L->getBlocks()[i];
1700 Loop *BBLoop = LI->getLoopFor(BB);
1702 printBasicBlock(BB);
1703 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1706 Out << " } while (1); /* end of syntactic loop '"
1707 << L->getHeader()->getName() << "' */\n";
1710 void CWriter::printBasicBlock(BasicBlock *BB) {
1712 // Don't print the label for the basic block if there are no uses, or if
1713 // the only terminator use is the predecessor basic block's terminator.
1714 // We have to scan the use list because PHI nodes use basic blocks too but
1715 // do not require a label to be generated.
1717 bool NeedsLabel = false;
1718 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1719 if (isGotoCodeNecessary(*PI, BB)) {
1724 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1726 // Output all of the instructions in the basic block...
1727 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1729 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1730 if (II->getType() != Type::VoidTy)
1739 // Don't emit prefix or suffix for the terminator...
1740 visit(*BB->getTerminator());
1744 // Specific Instruction type classes... note that all of the casts are
1745 // necessary because we use the instruction classes as opaque types...
1747 void CWriter::visitReturnInst(ReturnInst &I) {
1748 // If this is a struct return function, return the temporary struct.
1749 if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
1750 Out << " return StructReturn;\n";
1754 // Don't output a void return if this is the last basic block in the function
1755 if (I.getNumOperands() == 0 &&
1756 &*--I.getParent()->getParent()->end() == I.getParent() &&
1757 !I.getParent()->size() == 1) {
1762 if (I.getNumOperands()) {
1764 writeOperand(I.getOperand(0));
1769 void CWriter::visitSwitchInst(SwitchInst &SI) {
1772 writeOperand(SI.getOperand(0));
1773 Out << ") {\n default:\n";
1774 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
1775 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1777 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1779 writeOperand(SI.getOperand(i));
1781 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1782 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
1783 printBranchToBlock(SI.getParent(), Succ, 2);
1784 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
1790 void CWriter::visitUnreachableInst(UnreachableInst &I) {
1791 Out << " /*UNREACHABLE*/;\n";
1794 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1795 /// FIXME: This should be reenabled, but loop reordering safe!!
1798 if (next(Function::iterator(From)) != Function::iterator(To))
1799 return true; // Not the direct successor, we need a goto.
1801 //isa<SwitchInst>(From->getTerminator())
1803 if (LI->getLoopFor(From) != LI->getLoopFor(To))
1808 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
1809 BasicBlock *Successor,
1811 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1812 PHINode *PN = cast<PHINode>(I);
1813 // Now we have to do the printing.
1814 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1815 if (!isa<UndefValue>(IV)) {
1816 Out << std::string(Indent, ' ');
1817 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1819 Out << "; /* for PHI node */\n";
1824 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1826 if (isGotoCodeNecessary(CurBB, Succ)) {
1827 Out << std::string(Indent, ' ') << " goto ";
1833 // Branch instruction printing - Avoid printing out a branch to a basic block
1834 // that immediately succeeds the current one.
1836 void CWriter::visitBranchInst(BranchInst &I) {
1838 if (I.isConditional()) {
1839 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1841 writeOperand(I.getCondition());
1844 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
1845 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1847 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1848 Out << " } else {\n";
1849 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1850 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1853 // First goto not necessary, assume second one is...
1855 writeOperand(I.getCondition());
1858 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1859 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1864 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
1865 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1870 // PHI nodes get copied into temporary values at the end of predecessor basic
1871 // blocks. We now need to copy these temporary values into the REAL value for
1873 void CWriter::visitPHINode(PHINode &I) {
1875 Out << "__PHI_TEMPORARY";
1879 void CWriter::visitBinaryOperator(Instruction &I) {
1880 // binary instructions, shift instructions, setCond instructions.
1881 assert(!isa<PointerType>(I.getType()));
1883 // We must cast the results of binary operations which might be promoted.
1884 bool needsCast = false;
1885 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1886 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1887 || (I.getType() == Type::FloatTy)) {
1890 printType(Out, I.getType());
1894 // If this is a negation operation, print it out as such. For FP, we don't
1895 // want to print "-0.0 - X".
1896 if (BinaryOperator::isNeg(&I)) {
1898 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
1900 } else if (I.getOpcode() == Instruction::FRem) {
1901 // Output a call to fmod/fmodf instead of emitting a%b
1902 if (I.getType() == Type::FloatTy)
1906 writeOperand(I.getOperand(0));
1908 writeOperand(I.getOperand(1));
1912 // Write out the cast of the instruction's value back to the proper type
1914 bool NeedsClosingParens = writeInstructionCast(I);
1916 // Certain instructions require the operand to be forced to a specific type
1917 // so we use writeOperandWithCast here instead of writeOperand. Similarly
1918 // below for operand 1
1919 writeOperandWithCast(I.getOperand(0), I.getOpcode());
1921 switch (I.getOpcode()) {
1922 case Instruction::Add: Out << " + "; break;
1923 case Instruction::Sub: Out << " - "; break;
1924 case Instruction::Mul: Out << '*'; break;
1925 case Instruction::URem:
1926 case Instruction::SRem:
1927 case Instruction::FRem: Out << '%'; break;
1928 case Instruction::UDiv:
1929 case Instruction::SDiv:
1930 case Instruction::FDiv: Out << '/'; break;
1931 case Instruction::And: Out << " & "; break;
1932 case Instruction::Or: Out << " | "; break;
1933 case Instruction::Xor: Out << " ^ "; break;
1934 case Instruction::SetEQ: Out << " == "; break;
1935 case Instruction::SetNE: Out << " != "; break;
1936 case Instruction::SetLE: Out << " <= "; break;
1937 case Instruction::SetGE: Out << " >= "; break;
1938 case Instruction::SetLT: Out << " < "; break;
1939 case Instruction::SetGT: Out << " > "; break;
1940 case Instruction::Shl : Out << " << "; break;
1941 case Instruction::LShr:
1942 case Instruction::AShr: Out << " >> "; break;
1943 default: std::cerr << "Invalid operator type!" << I; abort();
1946 writeOperandWithCast(I.getOperand(1), I.getOpcode());
1947 if (NeedsClosingParens)
1956 void CWriter::visitCastInst(CastInst &I) {
1957 const Type *DstTy = I.getType();
1958 const Type *SrcTy = I.getOperand(0)->getType();
1960 printCast(I.getOpcode(), SrcTy, DstTy);
1961 if (I.getOpcode() == Instruction::SExt && SrcTy == Type::BoolTy) {
1962 // Make sure we really get a sext from bool by subtracing the bool from 0
1965 writeOperand(I.getOperand(0));
1966 if (DstTy == Type::BoolTy &&
1967 (I.getOpcode() == Instruction::Trunc ||
1968 I.getOpcode() == Instruction::FPToUI ||
1969 I.getOpcode() == Instruction::FPToSI ||
1970 I.getOpcode() == Instruction::PtrToInt)) {
1971 // Make sure we really get a trunc to bool by anding the operand with 1
1977 void CWriter::visitSelectInst(SelectInst &I) {
1979 writeOperand(I.getCondition());
1981 writeOperand(I.getTrueValue());
1983 writeOperand(I.getFalseValue());
1988 void CWriter::lowerIntrinsics(Function &F) {
1989 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1990 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1991 if (CallInst *CI = dyn_cast<CallInst>(I++))
1992 if (Function *F = CI->getCalledFunction())
1993 switch (F->getIntrinsicID()) {
1994 case Intrinsic::not_intrinsic:
1995 case Intrinsic::vastart:
1996 case Intrinsic::vacopy:
1997 case Intrinsic::vaend:
1998 case Intrinsic::returnaddress:
1999 case Intrinsic::frameaddress:
2000 case Intrinsic::setjmp:
2001 case Intrinsic::longjmp:
2002 case Intrinsic::prefetch:
2003 case Intrinsic::dbg_stoppoint:
2004 case Intrinsic::powi_f32:
2005 case Intrinsic::powi_f64:
2006 // We directly implement these intrinsics
2009 // If this is an intrinsic that directly corresponds to a GCC
2010 // builtin, we handle it.
2011 const char *BuiltinName = "";
2012 #define GET_GCC_BUILTIN_NAME
2013 #include "llvm/Intrinsics.gen"
2014 #undef GET_GCC_BUILTIN_NAME
2015 // If we handle it, don't lower it.
2016 if (BuiltinName[0]) break;
2018 // All other intrinsic calls we must lower.
2019 Instruction *Before = 0;
2020 if (CI != &BB->front())
2021 Before = prior(BasicBlock::iterator(CI));
2023 IL.LowerIntrinsicCall(CI);
2024 if (Before) { // Move iterator to instruction after call
2035 void CWriter::visitCallInst(CallInst &I) {
2036 bool WroteCallee = false;
2038 // Handle intrinsic function calls first...
2039 if (Function *F = I.getCalledFunction())
2040 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
2043 // If this is an intrinsic that directly corresponds to a GCC
2044 // builtin, we emit it here.
2045 const char *BuiltinName = "";
2046 #define GET_GCC_BUILTIN_NAME
2047 #include "llvm/Intrinsics.gen"
2048 #undef GET_GCC_BUILTIN_NAME
2049 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2055 case Intrinsic::vastart:
2058 Out << "va_start(*(va_list*)";
2059 writeOperand(I.getOperand(1));
2061 // Output the last argument to the enclosing function...
2062 if (I.getParent()->getParent()->arg_empty()) {
2063 std::cerr << "The C backend does not currently support zero "
2064 << "argument varargs functions, such as '"
2065 << I.getParent()->getParent()->getName() << "'!\n";
2068 writeOperand(--I.getParent()->getParent()->arg_end());
2071 case Intrinsic::vaend:
2072 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2073 Out << "0; va_end(*(va_list*)";
2074 writeOperand(I.getOperand(1));
2077 Out << "va_end(*(va_list*)0)";
2080 case Intrinsic::vacopy:
2082 Out << "va_copy(*(va_list*)";
2083 writeOperand(I.getOperand(1));
2084 Out << ", *(va_list*)";
2085 writeOperand(I.getOperand(2));
2088 case Intrinsic::returnaddress:
2089 Out << "__builtin_return_address(";
2090 writeOperand(I.getOperand(1));
2093 case Intrinsic::frameaddress:
2094 Out << "__builtin_frame_address(";
2095 writeOperand(I.getOperand(1));
2098 case Intrinsic::powi_f32:
2099 case Intrinsic::powi_f64:
2100 Out << "__builtin_powi(";
2101 writeOperand(I.getOperand(1));
2103 writeOperand(I.getOperand(2));
2106 case Intrinsic::setjmp:
2107 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
2108 Out << "_"; // Use _setjmp on systems that support it!
2110 Out << "setjmp(*(jmp_buf*)";
2111 writeOperand(I.getOperand(1));
2114 case Intrinsic::longjmp:
2115 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
2116 Out << "_"; // Use _longjmp on systems that support it!
2118 Out << "longjmp(*(jmp_buf*)";
2119 writeOperand(I.getOperand(1));
2121 writeOperand(I.getOperand(2));
2124 case Intrinsic::prefetch:
2125 Out << "LLVM_PREFETCH((const void *)";
2126 writeOperand(I.getOperand(1));
2128 writeOperand(I.getOperand(2));
2130 writeOperand(I.getOperand(3));
2133 case Intrinsic::dbg_stoppoint: {
2134 // If we use writeOperand directly we get a "u" suffix which is rejected
2136 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2140 << " \"" << SPI.getDirectory()
2141 << SPI.getFileName() << "\"\n";
2147 Value *Callee = I.getCalledValue();
2149 // If this is a call to a struct-return function, assign to the first
2150 // parameter instead of passing it to the call.
2151 bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
2154 writeOperand(I.getOperand(1));
2158 if (I.isTailCall()) Out << " /*tail*/ ";
2160 const PointerType *PTy = cast<PointerType>(Callee->getType());
2161 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2164 // If this is an indirect call to a struct return function, we need to cast
2166 bool NeedsCast = isStructRet && !isa<Function>(Callee);
2168 // GCC is a real PITA. It does not permit codegening casts of functions to
2169 // function pointers if they are in a call (it generates a trap instruction
2170 // instead!). We work around this by inserting a cast to void* in between
2171 // the function and the function pointer cast. Unfortunately, we can't just
2172 // form the constant expression here, because the folder will immediately
2175 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2176 // that void* and function pointers have the same size. :( To deal with this
2177 // in the common case, we handle casts where the number of arguments passed
2180 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2182 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2188 // Ok, just cast the pointer type.
2191 printType(Out, I.getCalledValue()->getType());
2193 printStructReturnPointerFunctionType(Out,
2194 cast<PointerType>(I.getCalledValue()->getType()));
2197 writeOperand(Callee);
2198 if (NeedsCast) Out << ')';
2203 unsigned NumDeclaredParams = FTy->getNumParams();
2205 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2207 if (isStructRet) { // Skip struct return argument.
2212 bool PrintedArg = false;
2213 for (; AI != AE; ++AI, ++ArgNo) {
2214 if (PrintedArg) Out << ", ";
2215 if (ArgNo < NumDeclaredParams &&
2216 (*AI)->getType() != FTy->getParamType(ArgNo)) {
2218 printType(Out, FTy->getParamType(ArgNo));
2227 void CWriter::visitMallocInst(MallocInst &I) {
2228 assert(0 && "lowerallocations pass didn't work!");
2231 void CWriter::visitAllocaInst(AllocaInst &I) {
2233 printType(Out, I.getType());
2234 Out << ") alloca(sizeof(";
2235 printType(Out, I.getType()->getElementType());
2237 if (I.isArrayAllocation()) {
2239 writeOperand(I.getOperand(0));
2244 void CWriter::visitFreeInst(FreeInst &I) {
2245 assert(0 && "lowerallocations pass didn't work!");
2248 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2249 gep_type_iterator E) {
2250 bool HasImplicitAddress = false;
2251 // If accessing a global value with no indexing, avoid *(&GV) syndrome
2252 if (isa<GlobalValue>(Ptr)) {
2253 HasImplicitAddress = true;
2254 } else if (isDirectAlloca(Ptr)) {
2255 HasImplicitAddress = true;
2259 if (!HasImplicitAddress)
2260 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
2262 writeOperandInternal(Ptr);
2266 const Constant *CI = dyn_cast<Constant>(I.getOperand());
2267 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2270 writeOperandInternal(Ptr);
2272 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
2274 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
2277 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
2278 "Can only have implicit address with direct accessing");
2280 if (HasImplicitAddress) {
2282 } else if (CI && CI->isNullValue()) {
2283 gep_type_iterator TmpI = I; ++TmpI;
2285 // Print out the -> operator if possible...
2286 if (TmpI != E && isa<StructType>(*TmpI)) {
2287 Out << (HasImplicitAddress ? "." : "->");
2288 Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
2294 if (isa<StructType>(*I)) {
2295 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
2298 writeOperand(I.getOperand());
2303 void CWriter::visitLoadInst(LoadInst &I) {
2305 if (I.isVolatile()) {
2307 printType(Out, I.getType(), "volatile*");
2311 writeOperand(I.getOperand(0));
2317 void CWriter::visitStoreInst(StoreInst &I) {
2319 if (I.isVolatile()) {
2321 printType(Out, I.getOperand(0)->getType(), " volatile*");
2324 writeOperand(I.getPointerOperand());
2325 if (I.isVolatile()) Out << ')';
2327 writeOperand(I.getOperand(0));
2330 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
2332 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2336 void CWriter::visitVAArgInst(VAArgInst &I) {
2337 Out << "va_arg(*(va_list*)";
2338 writeOperand(I.getOperand(0));
2340 printType(Out, I.getType());
2344 //===----------------------------------------------------------------------===//
2345 // External Interface declaration
2346 //===----------------------------------------------------------------------===//
2348 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2350 CodeGenFileType FileType,
2352 if (FileType != TargetMachine::AssemblyFile) return true;
2354 PM.add(createLowerGCPass());
2355 PM.add(createLowerAllocationsPass(true));
2356 PM.add(createLowerInvokePass());
2357 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
2358 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
2359 PM.add(new CWriter(o));