1 //===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library converts LLVM code to C code, compilable by GCC and other C
13 //===----------------------------------------------------------------------===//
15 #include "CTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/Analysis/ConstantsScanner.h"
31 #include "llvm/Analysis/FindUsedTypes.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/Target/Mangler.h"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCSubtargetInfo.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Target/TargetRegistry.h"
44 #include "llvm/Support/CallSite.h"
45 #include "llvm/Support/CFG.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/FormattedStream.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Support/InstVisitor.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/Host.h"
52 #include "llvm/Config/config.h"
54 // Some ms header decided to define setjmp as _setjmp, undo this for this file.
60 extern "C" void LLVMInitializeCBackendTarget() {
61 // Register the target.
62 RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
65 extern "C" void LLVMInitializeCBackendMCSubtargetInfo() {
66 RegisterMCSubtargetInfo<MCSubtargetInfo> X(TheCBackendTarget);
70 class CBEMCAsmInfo : public MCAsmInfo {
74 PrivateGlobalPrefix = "";
77 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
78 /// any unnamed structure types that are used by the program, and merges
79 /// external functions with the same name.
81 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
84 CBackendNameAllUsedStructsAndMergeFunctions()
86 initializeFindUsedTypesPass(*PassRegistry::getPassRegistry());
88 void getAnalysisUsage(AnalysisUsage &AU) const {
89 AU.addRequired<FindUsedTypes>();
92 virtual const char *getPassName() const {
93 return "C backend type canonicalizer";
96 virtual bool runOnModule(Module &M);
99 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
101 /// CWriter - This class is the main chunk of code that converts an LLVM
102 /// module to a C translation unit.
103 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
104 formatted_raw_ostream &Out;
105 IntrinsicLowering *IL;
108 const Module *TheModule;
109 const MCAsmInfo* TAsm;
111 const TargetData* TD;
112 std::map<const Type *, std::string> TypeNames;
113 std::map<const ConstantFP *, unsigned> FPConstantMap;
114 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
115 std::set<const Argument*> ByValParams;
117 unsigned OpaqueCounter;
118 DenseMap<const Value*, unsigned> AnonValueNumbers;
119 unsigned NextAnonValueNumber;
123 explicit CWriter(formatted_raw_ostream &o)
124 : FunctionPass(ID), Out(o), IL(0), Mang(0), LI(0),
125 TheModule(0), TAsm(0), TCtx(0), TD(0), OpaqueCounter(0),
126 NextAnonValueNumber(0) {
127 initializeLoopInfoPass(*PassRegistry::getPassRegistry());
131 virtual const char *getPassName() const { return "C backend"; }
133 void getAnalysisUsage(AnalysisUsage &AU) const {
134 AU.addRequired<LoopInfo>();
135 AU.setPreservesAll();
138 virtual bool doInitialization(Module &M);
140 bool runOnFunction(Function &F) {
141 // Do not codegen any 'available_externally' functions at all, they have
142 // definitions outside the translation unit.
143 if (F.hasAvailableExternallyLinkage())
146 LI = &getAnalysis<LoopInfo>();
148 // Get rid of intrinsics we can't handle.
151 // Output all floating point constants that cannot be printed accurately.
152 printFloatingPointConstants(F);
158 virtual bool doFinalization(Module &M) {
165 FPConstantMap.clear();
168 intrinsicPrototypesAlreadyGenerated.clear();
172 raw_ostream &printType(raw_ostream &Out, const Type *Ty,
173 bool isSigned = false,
174 const std::string &VariableName = "",
175 bool IgnoreName = false,
176 const AttrListPtr &PAL = AttrListPtr());
177 raw_ostream &printSimpleType(raw_ostream &Out, const Type *Ty,
179 const std::string &NameSoFar = "");
181 void printStructReturnPointerFunctionType(raw_ostream &Out,
182 const AttrListPtr &PAL,
183 const PointerType *Ty);
185 /// writeOperandDeref - Print the result of dereferencing the specified
186 /// operand with '*'. This is equivalent to printing '*' then using
187 /// writeOperand, but avoids excess syntax in some cases.
188 void writeOperandDeref(Value *Operand) {
189 if (isAddressExposed(Operand)) {
190 // Already something with an address exposed.
191 writeOperandInternal(Operand);
194 writeOperand(Operand);
199 void writeOperand(Value *Operand, bool Static = false);
200 void writeInstComputationInline(Instruction &I);
201 void writeOperandInternal(Value *Operand, bool Static = false);
202 void writeOperandWithCast(Value* Operand, unsigned Opcode);
203 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
204 bool writeInstructionCast(const Instruction &I);
206 void writeMemoryAccess(Value *Operand, const Type *OperandType,
207 bool IsVolatile, unsigned Alignment);
210 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
212 void lowerIntrinsics(Function &F);
213 /// Prints the definition of the intrinsic function F. Supports the
214 /// intrinsics which need to be explicitly defined in the CBackend.
215 void printIntrinsicDefinition(const Function &F, raw_ostream &Out);
217 void printModuleTypes(const TypeSymbolTable &ST);
218 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
219 void printFloatingPointConstants(Function &F);
220 void printFloatingPointConstants(const Constant *C);
221 void printFunctionSignature(const Function *F, bool Prototype);
223 void printFunction(Function &);
224 void printBasicBlock(BasicBlock *BB);
225 void printLoop(Loop *L);
227 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
228 void printConstant(Constant *CPV, bool Static);
229 void printConstantWithCast(Constant *CPV, unsigned Opcode);
230 bool printConstExprCast(const ConstantExpr *CE, bool Static);
231 void printConstantArray(ConstantArray *CPA, bool Static);
232 void printConstantVector(ConstantVector *CV, bool Static);
234 /// isAddressExposed - Return true if the specified value's name needs to
235 /// have its address taken in order to get a C value of the correct type.
236 /// This happens for global variables, byval parameters, and direct allocas.
237 bool isAddressExposed(const Value *V) const {
238 if (const Argument *A = dyn_cast<Argument>(V))
239 return ByValParams.count(A);
240 return isa<GlobalVariable>(V) || isDirectAlloca(V);
243 // isInlinableInst - Attempt to inline instructions into their uses to build
244 // trees as much as possible. To do this, we have to consistently decide
245 // what is acceptable to inline, so that variable declarations don't get
246 // printed and an extra copy of the expr is not emitted.
248 static bool isInlinableInst(const Instruction &I) {
249 // Always inline cmp instructions, even if they are shared by multiple
250 // expressions. GCC generates horrible code if we don't.
254 // Must be an expression, must be used exactly once. If it is dead, we
255 // emit it inline where it would go.
256 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
257 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
258 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
259 isa<InsertValueInst>(I))
260 // Don't inline a load across a store or other bad things!
263 // Must not be used in inline asm, extractelement, or shufflevector.
265 const Instruction &User = cast<Instruction>(*I.use_back());
266 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
267 isa<ShuffleVectorInst>(User))
271 // Only inline instruction it if it's use is in the same BB as the inst.
272 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
275 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
276 // variables which are accessed with the & operator. This causes GCC to
277 // generate significantly better code than to emit alloca calls directly.
279 static const AllocaInst *isDirectAlloca(const Value *V) {
280 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
282 if (AI->isArrayAllocation())
283 return 0; // FIXME: we can also inline fixed size array allocas!
284 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
289 // isInlineAsm - Check if the instruction is a call to an inline asm chunk.
290 static bool isInlineAsm(const Instruction& I) {
291 if (const CallInst *CI = dyn_cast<CallInst>(&I))
292 return isa<InlineAsm>(CI->getCalledValue());
296 // Instruction visitation functions
297 friend class InstVisitor<CWriter>;
299 void visitReturnInst(ReturnInst &I);
300 void visitBranchInst(BranchInst &I);
301 void visitSwitchInst(SwitchInst &I);
302 void visitIndirectBrInst(IndirectBrInst &I);
303 void visitInvokeInst(InvokeInst &I) {
304 llvm_unreachable("Lowerinvoke pass didn't work!");
307 void visitUnwindInst(UnwindInst &I) {
308 llvm_unreachable("Lowerinvoke pass didn't work!");
310 void visitUnreachableInst(UnreachableInst &I);
312 void visitPHINode(PHINode &I);
313 void visitBinaryOperator(Instruction &I);
314 void visitICmpInst(ICmpInst &I);
315 void visitFCmpInst(FCmpInst &I);
317 void visitCastInst (CastInst &I);
318 void visitSelectInst(SelectInst &I);
319 void visitCallInst (CallInst &I);
320 void visitInlineAsm(CallInst &I);
321 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
323 void visitAllocaInst(AllocaInst &I);
324 void visitLoadInst (LoadInst &I);
325 void visitStoreInst (StoreInst &I);
326 void visitGetElementPtrInst(GetElementPtrInst &I);
327 void visitVAArgInst (VAArgInst &I);
329 void visitInsertElementInst(InsertElementInst &I);
330 void visitExtractElementInst(ExtractElementInst &I);
331 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
333 void visitInsertValueInst(InsertValueInst &I);
334 void visitExtractValueInst(ExtractValueInst &I);
336 void visitInstruction(Instruction &I) {
338 errs() << "C Writer does not know about " << I;
343 void outputLValue(Instruction *I) {
344 Out << " " << GetValueName(I) << " = ";
347 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
348 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
349 BasicBlock *Successor, unsigned Indent);
350 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
352 void printGEPExpression(Value *Ptr, gep_type_iterator I,
353 gep_type_iterator E, bool Static);
355 std::string GetValueName(const Value *Operand);
359 char CWriter::ID = 0;
362 static std::string CBEMangle(const std::string &S) {
365 for (unsigned i = 0, e = S.size(); i != e; ++i)
366 if (isalnum(S[i]) || S[i] == '_') {
370 Result += 'A'+(S[i]&15);
371 Result += 'A'+((S[i]>>4)&15);
378 /// This method inserts names for any unnamed structure types that are used by
379 /// the program, and removes names from structure types that are not used by the
382 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
383 // Get a set of types that are used by the program...
384 SetVector<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
386 // Loop over the module symbol table, removing types from UT that are
387 // already named, and removing names for types that are not used.
389 TypeSymbolTable &TST = M.getTypeSymbolTable();
390 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
392 TypeSymbolTable::iterator I = TI++;
394 // If this isn't a struct or array type, remove it from our set of types
395 // to name. This simplifies emission later.
396 if (!I->second->isStructTy() && !I->second->isOpaqueTy() &&
397 !I->second->isArrayTy()) {
400 // If this is not used, remove it from the symbol table.
401 if (!UT.count(I->second))
404 UT.remove(I->second); // Only keep one name for this type.
408 // UT now contains types that are not named. Loop over it, naming
411 bool Changed = false;
412 unsigned RenameCounter = 0;
413 for (SetVector<const Type *>::const_iterator I = UT.begin(), E = UT.end();
415 if ((*I)->isStructTy() || (*I)->isArrayTy()) {
416 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
422 // Loop over all external functions and globals. If we have two with
423 // identical names, merge them.
424 // FIXME: This code should disappear when we don't allow values with the same
425 // names when they have different types!
426 std::map<std::string, GlobalValue*> ExtSymbols;
427 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
429 if (GV->isDeclaration() && GV->hasName()) {
430 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
431 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
433 // Found a conflict, replace this global with the previous one.
434 GlobalValue *OldGV = X.first->second;
435 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
436 GV->eraseFromParent();
441 // Do the same for globals.
442 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
444 GlobalVariable *GV = I++;
445 if (GV->isDeclaration() && GV->hasName()) {
446 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
447 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
449 // Found a conflict, replace this global with the previous one.
450 GlobalValue *OldGV = X.first->second;
451 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
452 GV->eraseFromParent();
461 /// printStructReturnPointerFunctionType - This is like printType for a struct
462 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
463 /// print it as "Struct (*)(...)", for struct return functions.
464 void CWriter::printStructReturnPointerFunctionType(raw_ostream &Out,
465 const AttrListPtr &PAL,
466 const PointerType *TheTy) {
467 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
469 raw_string_ostream FunctionInnards(tstr);
470 FunctionInnards << " (*) (";
471 bool PrintedType = false;
473 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
474 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
476 for (++I, ++Idx; I != E; ++I, ++Idx) {
478 FunctionInnards << ", ";
479 const Type *ArgTy = *I;
480 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
481 assert(ArgTy->isPointerTy());
482 ArgTy = cast<PointerType>(ArgTy)->getElementType();
484 printType(FunctionInnards, ArgTy,
485 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
488 if (FTy->isVarArg()) {
490 FunctionInnards << " int"; //dummy argument for empty vararg functs
491 FunctionInnards << ", ...";
492 } else if (!PrintedType) {
493 FunctionInnards << "void";
495 FunctionInnards << ')';
496 printType(Out, RetTy,
497 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), FunctionInnards.str());
501 CWriter::printSimpleType(raw_ostream &Out, const Type *Ty, bool isSigned,
502 const std::string &NameSoFar) {
503 assert((Ty->isPrimitiveType() || Ty->isIntegerTy() || Ty->isVectorTy()) &&
504 "Invalid type for printSimpleType");
505 switch (Ty->getTypeID()) {
506 case Type::VoidTyID: return Out << "void " << NameSoFar;
507 case Type::IntegerTyID: {
508 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
510 return Out << "bool " << NameSoFar;
511 else if (NumBits <= 8)
512 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
513 else if (NumBits <= 16)
514 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
515 else if (NumBits <= 32)
516 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
517 else if (NumBits <= 64)
518 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
520 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
521 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
524 case Type::FloatTyID: return Out << "float " << NameSoFar;
525 case Type::DoubleTyID: return Out << "double " << NameSoFar;
526 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
527 // present matches host 'long double'.
528 case Type::X86_FP80TyID:
529 case Type::PPC_FP128TyID:
530 case Type::FP128TyID: return Out << "long double " << NameSoFar;
532 case Type::X86_MMXTyID:
533 return printSimpleType(Out, Type::getInt32Ty(Ty->getContext()), isSigned,
534 " __attribute__((vector_size(64))) " + NameSoFar);
536 case Type::VectorTyID: {
537 const VectorType *VTy = cast<VectorType>(Ty);
538 return printSimpleType(Out, VTy->getElementType(), isSigned,
539 " __attribute__((vector_size(" +
540 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
545 errs() << "Unknown primitive type: " << *Ty << "\n";
551 // Pass the Type* and the variable name and this prints out the variable
554 raw_ostream &CWriter::printType(raw_ostream &Out, const Type *Ty,
555 bool isSigned, const std::string &NameSoFar,
556 bool IgnoreName, const AttrListPtr &PAL) {
557 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || Ty->isVectorTy()) {
558 printSimpleType(Out, Ty, isSigned, NameSoFar);
562 // Check to see if the type is named.
563 if (!IgnoreName || Ty->isOpaqueTy()) {
564 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
565 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
568 switch (Ty->getTypeID()) {
569 case Type::FunctionTyID: {
570 const FunctionType *FTy = cast<FunctionType>(Ty);
572 raw_string_ostream FunctionInnards(tstr);
573 FunctionInnards << " (" << NameSoFar << ") (";
575 for (FunctionType::param_iterator I = FTy->param_begin(),
576 E = FTy->param_end(); I != E; ++I) {
577 const Type *ArgTy = *I;
578 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
579 assert(ArgTy->isPointerTy());
580 ArgTy = cast<PointerType>(ArgTy)->getElementType();
582 if (I != FTy->param_begin())
583 FunctionInnards << ", ";
584 printType(FunctionInnards, ArgTy,
585 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
588 if (FTy->isVarArg()) {
589 if (!FTy->getNumParams())
590 FunctionInnards << " int"; //dummy argument for empty vaarg functs
591 FunctionInnards << ", ...";
592 } else if (!FTy->getNumParams()) {
593 FunctionInnards << "void";
595 FunctionInnards << ')';
596 printType(Out, FTy->getReturnType(),
597 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), FunctionInnards.str());
600 case Type::StructTyID: {
601 const StructType *STy = cast<StructType>(Ty);
602 Out << NameSoFar + " {\n";
604 for (StructType::element_iterator I = STy->element_begin(),
605 E = STy->element_end(); I != E; ++I) {
607 printType(Out, *I, false, "field" + utostr(Idx++));
612 Out << " __attribute__ ((packed))";
616 case Type::PointerTyID: {
617 const PointerType *PTy = cast<PointerType>(Ty);
618 std::string ptrName = "*" + NameSoFar;
620 if (PTy->getElementType()->isArrayTy() ||
621 PTy->getElementType()->isVectorTy())
622 ptrName = "(" + ptrName + ")";
625 // Must be a function ptr cast!
626 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
627 return printType(Out, PTy->getElementType(), false, ptrName);
630 case Type::ArrayTyID: {
631 const ArrayType *ATy = cast<ArrayType>(Ty);
632 unsigned NumElements = ATy->getNumElements();
633 if (NumElements == 0) NumElements = 1;
634 // Arrays are wrapped in structs to allow them to have normal
635 // value semantics (avoiding the array "decay").
636 Out << NameSoFar << " { ";
637 printType(Out, ATy->getElementType(), false,
638 "array[" + utostr(NumElements) + "]");
642 case Type::OpaqueTyID: {
643 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
644 assert(TypeNames.find(Ty) == TypeNames.end());
645 TypeNames[Ty] = TyName;
646 return Out << TyName << ' ' << NameSoFar;
649 llvm_unreachable("Unhandled case in getTypeProps!");
655 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
657 // As a special case, print the array as a string if it is an array of
658 // ubytes or an array of sbytes with positive values.
660 const Type *ETy = CPA->getType()->getElementType();
661 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
662 ETy == Type::getInt8Ty(CPA->getContext()));
664 // Make sure the last character is a null char, as automatically added by C
665 if (isString && (CPA->getNumOperands() == 0 ||
666 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
671 // Keep track of whether the last number was a hexadecimal escape.
672 bool LastWasHex = false;
674 // Do not include the last character, which we know is null
675 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
676 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
678 // Print it out literally if it is a printable character. The only thing
679 // to be careful about is when the last letter output was a hex escape
680 // code, in which case we have to be careful not to print out hex digits
681 // explicitly (the C compiler thinks it is a continuation of the previous
682 // character, sheesh...)
684 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
686 if (C == '"' || C == '\\')
687 Out << "\\" << (char)C;
693 case '\n': Out << "\\n"; break;
694 case '\t': Out << "\\t"; break;
695 case '\r': Out << "\\r"; break;
696 case '\v': Out << "\\v"; break;
697 case '\a': Out << "\\a"; break;
698 case '\"': Out << "\\\""; break;
699 case '\'': Out << "\\\'"; break;
702 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
703 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
712 if (CPA->getNumOperands()) {
714 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
715 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
717 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
724 void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
726 if (CP->getNumOperands()) {
728 printConstant(cast<Constant>(CP->getOperand(0)), Static);
729 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
731 printConstant(cast<Constant>(CP->getOperand(i)), Static);
737 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
738 // textually as a double (rather than as a reference to a stack-allocated
739 // variable). We decide this by converting CFP to a string and back into a
740 // double, and then checking whether the conversion results in a bit-equal
741 // double to the original value of CFP. This depends on us and the target C
742 // compiler agreeing on the conversion process (which is pretty likely since we
743 // only deal in IEEE FP).
745 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
747 // Do long doubles in hex for now.
748 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
749 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
751 APFloat APF = APFloat(CFP->getValueAPF()); // copy
752 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
753 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
754 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
756 sprintf(Buffer, "%a", APF.convertToDouble());
757 if (!strncmp(Buffer, "0x", 2) ||
758 !strncmp(Buffer, "-0x", 3) ||
759 !strncmp(Buffer, "+0x", 3))
760 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
763 std::string StrVal = ftostr(APF);
765 while (StrVal[0] == ' ')
766 StrVal.erase(StrVal.begin());
768 // Check to make sure that the stringized number is not some string like "Inf"
769 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
770 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
771 ((StrVal[0] == '-' || StrVal[0] == '+') &&
772 (StrVal[1] >= '0' && StrVal[1] <= '9')))
773 // Reparse stringized version!
774 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
779 /// Print out the casting for a cast operation. This does the double casting
780 /// necessary for conversion to the destination type, if necessary.
781 /// @brief Print a cast
782 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
783 // Print the destination type cast
785 case Instruction::UIToFP:
786 case Instruction::SIToFP:
787 case Instruction::IntToPtr:
788 case Instruction::Trunc:
789 case Instruction::BitCast:
790 case Instruction::FPExt:
791 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
793 printType(Out, DstTy);
796 case Instruction::ZExt:
797 case Instruction::PtrToInt:
798 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
800 printSimpleType(Out, DstTy, false);
803 case Instruction::SExt:
804 case Instruction::FPToSI: // For these, make sure we get a signed dest
806 printSimpleType(Out, DstTy, true);
810 llvm_unreachable("Invalid cast opcode");
813 // Print the source type cast
815 case Instruction::UIToFP:
816 case Instruction::ZExt:
818 printSimpleType(Out, SrcTy, false);
821 case Instruction::SIToFP:
822 case Instruction::SExt:
824 printSimpleType(Out, SrcTy, true);
827 case Instruction::IntToPtr:
828 case Instruction::PtrToInt:
829 // Avoid "cast to pointer from integer of different size" warnings
830 Out << "(unsigned long)";
832 case Instruction::Trunc:
833 case Instruction::BitCast:
834 case Instruction::FPExt:
835 case Instruction::FPTrunc:
836 case Instruction::FPToSI:
837 case Instruction::FPToUI:
838 break; // These don't need a source cast.
840 llvm_unreachable("Invalid cast opcode");
845 // printConstant - The LLVM Constant to C Constant converter.
846 void CWriter::printConstant(Constant *CPV, bool Static) {
847 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
848 switch (CE->getOpcode()) {
849 case Instruction::Trunc:
850 case Instruction::ZExt:
851 case Instruction::SExt:
852 case Instruction::FPTrunc:
853 case Instruction::FPExt:
854 case Instruction::UIToFP:
855 case Instruction::SIToFP:
856 case Instruction::FPToUI:
857 case Instruction::FPToSI:
858 case Instruction::PtrToInt:
859 case Instruction::IntToPtr:
860 case Instruction::BitCast:
862 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
863 if (CE->getOpcode() == Instruction::SExt &&
864 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
865 // Make sure we really sext from bool here by subtracting from 0
868 printConstant(CE->getOperand(0), Static);
869 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
870 (CE->getOpcode() == Instruction::Trunc ||
871 CE->getOpcode() == Instruction::FPToUI ||
872 CE->getOpcode() == Instruction::FPToSI ||
873 CE->getOpcode() == Instruction::PtrToInt)) {
874 // Make sure we really truncate to bool here by anding with 1
880 case Instruction::GetElementPtr:
882 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
883 gep_type_end(CPV), Static);
886 case Instruction::Select:
888 printConstant(CE->getOperand(0), Static);
890 printConstant(CE->getOperand(1), Static);
892 printConstant(CE->getOperand(2), Static);
895 case Instruction::Add:
896 case Instruction::FAdd:
897 case Instruction::Sub:
898 case Instruction::FSub:
899 case Instruction::Mul:
900 case Instruction::FMul:
901 case Instruction::SDiv:
902 case Instruction::UDiv:
903 case Instruction::FDiv:
904 case Instruction::URem:
905 case Instruction::SRem:
906 case Instruction::FRem:
907 case Instruction::And:
908 case Instruction::Or:
909 case Instruction::Xor:
910 case Instruction::ICmp:
911 case Instruction::Shl:
912 case Instruction::LShr:
913 case Instruction::AShr:
916 bool NeedsClosingParens = printConstExprCast(CE, Static);
917 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
918 switch (CE->getOpcode()) {
919 case Instruction::Add:
920 case Instruction::FAdd: Out << " + "; break;
921 case Instruction::Sub:
922 case Instruction::FSub: Out << " - "; break;
923 case Instruction::Mul:
924 case Instruction::FMul: Out << " * "; break;
925 case Instruction::URem:
926 case Instruction::SRem:
927 case Instruction::FRem: Out << " % "; break;
928 case Instruction::UDiv:
929 case Instruction::SDiv:
930 case Instruction::FDiv: Out << " / "; break;
931 case Instruction::And: Out << " & "; break;
932 case Instruction::Or: Out << " | "; break;
933 case Instruction::Xor: Out << " ^ "; break;
934 case Instruction::Shl: Out << " << "; break;
935 case Instruction::LShr:
936 case Instruction::AShr: Out << " >> "; break;
937 case Instruction::ICmp:
938 switch (CE->getPredicate()) {
939 case ICmpInst::ICMP_EQ: Out << " == "; break;
940 case ICmpInst::ICMP_NE: Out << " != "; break;
941 case ICmpInst::ICMP_SLT:
942 case ICmpInst::ICMP_ULT: Out << " < "; break;
943 case ICmpInst::ICMP_SLE:
944 case ICmpInst::ICMP_ULE: Out << " <= "; break;
945 case ICmpInst::ICMP_SGT:
946 case ICmpInst::ICMP_UGT: Out << " > "; break;
947 case ICmpInst::ICMP_SGE:
948 case ICmpInst::ICMP_UGE: Out << " >= "; break;
949 default: llvm_unreachable("Illegal ICmp predicate");
952 default: llvm_unreachable("Illegal opcode here!");
954 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
955 if (NeedsClosingParens)
960 case Instruction::FCmp: {
962 bool NeedsClosingParens = printConstExprCast(CE, Static);
963 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
965 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
969 switch (CE->getPredicate()) {
970 default: llvm_unreachable("Illegal FCmp predicate");
971 case FCmpInst::FCMP_ORD: op = "ord"; break;
972 case FCmpInst::FCMP_UNO: op = "uno"; break;
973 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
974 case FCmpInst::FCMP_UNE: op = "une"; break;
975 case FCmpInst::FCMP_ULT: op = "ult"; break;
976 case FCmpInst::FCMP_ULE: op = "ule"; break;
977 case FCmpInst::FCMP_UGT: op = "ugt"; break;
978 case FCmpInst::FCMP_UGE: op = "uge"; break;
979 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
980 case FCmpInst::FCMP_ONE: op = "one"; break;
981 case FCmpInst::FCMP_OLT: op = "olt"; break;
982 case FCmpInst::FCMP_OLE: op = "ole"; break;
983 case FCmpInst::FCMP_OGT: op = "ogt"; break;
984 case FCmpInst::FCMP_OGE: op = "oge"; break;
986 Out << "llvm_fcmp_" << op << "(";
987 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
989 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
992 if (NeedsClosingParens)
999 errs() << "CWriter Error: Unhandled constant expression: "
1002 llvm_unreachable(0);
1004 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
1006 printType(Out, CPV->getType()); // sign doesn't matter
1007 Out << ")/*UNDEF*/";
1008 if (!CPV->getType()->isVectorTy()) {
1016 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1017 const Type* Ty = CI->getType();
1018 if (Ty == Type::getInt1Ty(CPV->getContext()))
1019 Out << (CI->getZExtValue() ? '1' : '0');
1020 else if (Ty == Type::getInt32Ty(CPV->getContext()))
1021 Out << CI->getZExtValue() << 'u';
1022 else if (Ty->getPrimitiveSizeInBits() > 32)
1023 Out << CI->getZExtValue() << "ull";
1026 printSimpleType(Out, Ty, false) << ')';
1027 if (CI->isMinValue(true))
1028 Out << CI->getZExtValue() << 'u';
1030 Out << CI->getSExtValue();
1036 switch (CPV->getType()->getTypeID()) {
1037 case Type::FloatTyID:
1038 case Type::DoubleTyID:
1039 case Type::X86_FP80TyID:
1040 case Type::PPC_FP128TyID:
1041 case Type::FP128TyID: {
1042 ConstantFP *FPC = cast<ConstantFP>(CPV);
1043 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1044 if (I != FPConstantMap.end()) {
1045 // Because of FP precision problems we must load from a stack allocated
1046 // value that holds the value in hex.
1047 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1049 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1052 << "*)&FPConstant" << I->second << ')';
1055 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
1056 V = FPC->getValueAPF().convertToFloat();
1057 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
1058 V = FPC->getValueAPF().convertToDouble();
1060 // Long double. Convert the number to double, discarding precision.
1061 // This is not awesome, but it at least makes the CBE output somewhat
1063 APFloat Tmp = FPC->getValueAPF();
1065 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1066 V = Tmp.convertToDouble();
1072 // FIXME the actual NaN bits should be emitted.
1073 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1075 const unsigned long QuietNaN = 0x7ff8UL;
1076 //const unsigned long SignalNaN = 0x7ff4UL;
1078 // We need to grab the first part of the FP #
1081 uint64_t ll = DoubleToBits(V);
1082 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1084 std::string Num(&Buffer[0], &Buffer[6]);
1085 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1087 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
1088 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1089 << Buffer << "\") /*nan*/ ";
1091 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1092 << Buffer << "\") /*nan*/ ";
1093 } else if (IsInf(V)) {
1095 if (V < 0) Out << '-';
1096 Out << "LLVM_INF" <<
1097 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
1101 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1102 // Print out the constant as a floating point number.
1104 sprintf(Buffer, "%a", V);
1107 Num = ftostr(FPC->getValueAPF());
1115 case Type::ArrayTyID:
1116 // Use C99 compound expression literal initializer syntax.
1119 printType(Out, CPV->getType());
1122 Out << "{ "; // Arrays are wrapped in struct types.
1123 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
1124 printConstantArray(CA, Static);
1126 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1127 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1129 if (AT->getNumElements()) {
1131 Constant *CZ = Constant::getNullValue(AT->getElementType());
1132 printConstant(CZ, Static);
1133 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1135 printConstant(CZ, Static);
1140 Out << " }"; // Arrays are wrapped in struct types.
1143 case Type::VectorTyID:
1144 // Use C99 compound expression literal initializer syntax.
1147 printType(Out, CPV->getType());
1150 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
1151 printConstantVector(CV, Static);
1153 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1154 const VectorType *VT = cast<VectorType>(CPV->getType());
1156 Constant *CZ = Constant::getNullValue(VT->getElementType());
1157 printConstant(CZ, Static);
1158 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1160 printConstant(CZ, Static);
1166 case Type::StructTyID:
1167 // Use C99 compound expression literal initializer syntax.
1170 printType(Out, CPV->getType());
1173 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1174 const StructType *ST = cast<StructType>(CPV->getType());
1176 if (ST->getNumElements()) {
1178 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
1179 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1181 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
1187 if (CPV->getNumOperands()) {
1189 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
1190 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1192 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
1199 case Type::PointerTyID:
1200 if (isa<ConstantPointerNull>(CPV)) {
1202 printType(Out, CPV->getType()); // sign doesn't matter
1203 Out << ")/*NULL*/0)";
1205 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1206 writeOperand(GV, Static);
1212 errs() << "Unknown constant type: " << *CPV << "\n";
1214 llvm_unreachable(0);
1218 // Some constant expressions need to be casted back to the original types
1219 // because their operands were casted to the expected type. This function takes
1220 // care of detecting that case and printing the cast for the ConstantExpr.
1221 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
1222 bool NeedsExplicitCast = false;
1223 const Type *Ty = CE->getOperand(0)->getType();
1224 bool TypeIsSigned = false;
1225 switch (CE->getOpcode()) {
1226 case Instruction::Add:
1227 case Instruction::Sub:
1228 case Instruction::Mul:
1229 // We need to cast integer arithmetic so that it is always performed
1230 // as unsigned, to avoid undefined behavior on overflow.
1231 case Instruction::LShr:
1232 case Instruction::URem:
1233 case Instruction::UDiv: NeedsExplicitCast = true; break;
1234 case Instruction::AShr:
1235 case Instruction::SRem:
1236 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1237 case Instruction::SExt:
1239 NeedsExplicitCast = true;
1240 TypeIsSigned = true;
1242 case Instruction::ZExt:
1243 case Instruction::Trunc:
1244 case Instruction::FPTrunc:
1245 case Instruction::FPExt:
1246 case Instruction::UIToFP:
1247 case Instruction::SIToFP:
1248 case Instruction::FPToUI:
1249 case Instruction::FPToSI:
1250 case Instruction::PtrToInt:
1251 case Instruction::IntToPtr:
1252 case Instruction::BitCast:
1254 NeedsExplicitCast = true;
1258 if (NeedsExplicitCast) {
1260 if (Ty->isIntegerTy() && Ty != Type::getInt1Ty(Ty->getContext()))
1261 printSimpleType(Out, Ty, TypeIsSigned);
1263 printType(Out, Ty); // not integer, sign doesn't matter
1266 return NeedsExplicitCast;
1269 // Print a constant assuming that it is the operand for a given Opcode. The
1270 // opcodes that care about sign need to cast their operands to the expected
1271 // type before the operation proceeds. This function does the casting.
1272 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1274 // Extract the operand's type, we'll need it.
1275 const Type* OpTy = CPV->getType();
1277 // Indicate whether to do the cast or not.
1278 bool shouldCast = false;
1279 bool typeIsSigned = false;
1281 // Based on the Opcode for which this Constant is being written, determine
1282 // the new type to which the operand should be casted by setting the value
1283 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1287 // for most instructions, it doesn't matter
1289 case Instruction::Add:
1290 case Instruction::Sub:
1291 case Instruction::Mul:
1292 // We need to cast integer arithmetic so that it is always performed
1293 // as unsigned, to avoid undefined behavior on overflow.
1294 case Instruction::LShr:
1295 case Instruction::UDiv:
1296 case Instruction::URem:
1299 case Instruction::AShr:
1300 case Instruction::SDiv:
1301 case Instruction::SRem:
1303 typeIsSigned = true;
1307 // Write out the casted constant if we should, otherwise just write the
1311 printSimpleType(Out, OpTy, typeIsSigned);
1313 printConstant(CPV, false);
1316 printConstant(CPV, false);
1319 std::string CWriter::GetValueName(const Value *Operand) {
1321 // Resolve potential alias.
1322 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Operand)) {
1323 if (const Value *V = GA->resolveAliasedGlobal(false))
1327 // Mangle globals with the standard mangler interface for LLC compatibility.
1328 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1329 SmallString<128> Str;
1330 Mang->getNameWithPrefix(Str, GV, false);
1331 return CBEMangle(Str.str().str());
1334 std::string Name = Operand->getName();
1336 if (Name.empty()) { // Assign unique names to local temporaries.
1337 unsigned &No = AnonValueNumbers[Operand];
1339 No = ++NextAnonValueNumber;
1340 Name = "tmp__" + utostr(No);
1343 std::string VarName;
1344 VarName.reserve(Name.capacity());
1346 for (std::string::iterator I = Name.begin(), E = Name.end();
1350 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1351 (ch >= '0' && ch <= '9') || ch == '_')) {
1353 sprintf(buffer, "_%x_", ch);
1359 return "llvm_cbe_" + VarName;
1362 /// writeInstComputationInline - Emit the computation for the specified
1363 /// instruction inline, with no destination provided.
1364 void CWriter::writeInstComputationInline(Instruction &I) {
1365 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1367 const Type *Ty = I.getType();
1368 if (Ty->isIntegerTy() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1369 Ty!=Type::getInt8Ty(I.getContext()) &&
1370 Ty!=Type::getInt16Ty(I.getContext()) &&
1371 Ty!=Type::getInt32Ty(I.getContext()) &&
1372 Ty!=Type::getInt64Ty(I.getContext()))) {
1373 report_fatal_error("The C backend does not currently support integer "
1374 "types of widths other than 1, 8, 16, 32, 64.\n"
1375 "This is being tracked as PR 4158.");
1378 // If this is a non-trivial bool computation, make sure to truncate down to
1379 // a 1 bit value. This is important because we want "add i1 x, y" to return
1380 // "0" when x and y are true, not "2" for example.
1381 bool NeedBoolTrunc = false;
1382 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1383 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1384 NeedBoolTrunc = true;
1396 void CWriter::writeOperandInternal(Value *Operand, bool Static) {
1397 if (Instruction *I = dyn_cast<Instruction>(Operand))
1398 // Should we inline this instruction to build a tree?
1399 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1401 writeInstComputationInline(*I);
1406 Constant* CPV = dyn_cast<Constant>(Operand);
1408 if (CPV && !isa<GlobalValue>(CPV))
1409 printConstant(CPV, Static);
1411 Out << GetValueName(Operand);
1414 void CWriter::writeOperand(Value *Operand, bool Static) {
1415 bool isAddressImplicit = isAddressExposed(Operand);
1416 if (isAddressImplicit)
1417 Out << "(&"; // Global variables are referenced as their addresses by llvm
1419 writeOperandInternal(Operand, Static);
1421 if (isAddressImplicit)
1425 // Some instructions need to have their result value casted back to the
1426 // original types because their operands were casted to the expected type.
1427 // This function takes care of detecting that case and printing the cast
1428 // for the Instruction.
1429 bool CWriter::writeInstructionCast(const Instruction &I) {
1430 const Type *Ty = I.getOperand(0)->getType();
1431 switch (I.getOpcode()) {
1432 case Instruction::Add:
1433 case Instruction::Sub:
1434 case Instruction::Mul:
1435 // We need to cast integer arithmetic so that it is always performed
1436 // as unsigned, to avoid undefined behavior on overflow.
1437 case Instruction::LShr:
1438 case Instruction::URem:
1439 case Instruction::UDiv:
1441 printSimpleType(Out, Ty, false);
1444 case Instruction::AShr:
1445 case Instruction::SRem:
1446 case Instruction::SDiv:
1448 printSimpleType(Out, Ty, true);
1456 // Write the operand with a cast to another type based on the Opcode being used.
1457 // This will be used in cases where an instruction has specific type
1458 // requirements (usually signedness) for its operands.
1459 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1461 // Extract the operand's type, we'll need it.
1462 const Type* OpTy = Operand->getType();
1464 // Indicate whether to do the cast or not.
1465 bool shouldCast = false;
1467 // Indicate whether the cast should be to a signed type or not.
1468 bool castIsSigned = false;
1470 // Based on the Opcode for which this Operand is being written, determine
1471 // the new type to which the operand should be casted by setting the value
1472 // of OpTy. If we change OpTy, also set shouldCast to true.
1475 // for most instructions, it doesn't matter
1477 case Instruction::Add:
1478 case Instruction::Sub:
1479 case Instruction::Mul:
1480 // We need to cast integer arithmetic so that it is always performed
1481 // as unsigned, to avoid undefined behavior on overflow.
1482 case Instruction::LShr:
1483 case Instruction::UDiv:
1484 case Instruction::URem: // Cast to unsigned first
1486 castIsSigned = false;
1488 case Instruction::GetElementPtr:
1489 case Instruction::AShr:
1490 case Instruction::SDiv:
1491 case Instruction::SRem: // Cast to signed first
1493 castIsSigned = true;
1497 // Write out the casted operand if we should, otherwise just write the
1501 printSimpleType(Out, OpTy, castIsSigned);
1503 writeOperand(Operand);
1506 writeOperand(Operand);
1509 // Write the operand with a cast to another type based on the icmp predicate
1511 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1512 // This has to do a cast to ensure the operand has the right signedness.
1513 // Also, if the operand is a pointer, we make sure to cast to an integer when
1514 // doing the comparison both for signedness and so that the C compiler doesn't
1515 // optimize things like "p < NULL" to false (p may contain an integer value
1517 bool shouldCast = Cmp.isRelational();
1519 // Write out the casted operand if we should, otherwise just write the
1522 writeOperand(Operand);
1526 // Should this be a signed comparison? If so, convert to signed.
1527 bool castIsSigned = Cmp.isSigned();
1529 // If the operand was a pointer, convert to a large integer type.
1530 const Type* OpTy = Operand->getType();
1531 if (OpTy->isPointerTy())
1532 OpTy = TD->getIntPtrType(Operand->getContext());
1535 printSimpleType(Out, OpTy, castIsSigned);
1537 writeOperand(Operand);
1541 // generateCompilerSpecificCode - This is where we add conditional compilation
1542 // directives to cater to specific compilers as need be.
1544 static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
1545 const TargetData *TD) {
1546 // Alloca is hard to get, and we don't want to include stdlib.h here.
1547 Out << "/* get a declaration for alloca */\n"
1548 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1549 << "#define alloca(x) __builtin_alloca((x))\n"
1550 << "#define _alloca(x) __builtin_alloca((x))\n"
1551 << "#elif defined(__APPLE__)\n"
1552 << "extern void *__builtin_alloca(unsigned long);\n"
1553 << "#define alloca(x) __builtin_alloca(x)\n"
1554 << "#define longjmp _longjmp\n"
1555 << "#define setjmp _setjmp\n"
1556 << "#elif defined(__sun__)\n"
1557 << "#if defined(__sparcv9)\n"
1558 << "extern void *__builtin_alloca(unsigned long);\n"
1560 << "extern void *__builtin_alloca(unsigned int);\n"
1562 << "#define alloca(x) __builtin_alloca(x)\n"
1563 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
1564 << "#define alloca(x) __builtin_alloca(x)\n"
1565 << "#elif defined(_MSC_VER)\n"
1566 << "#define inline _inline\n"
1567 << "#define alloca(x) _alloca(x)\n"
1569 << "#include <alloca.h>\n"
1572 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1573 // If we aren't being compiled with GCC, just drop these attributes.
1574 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1575 << "#define __attribute__(X)\n"
1578 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1579 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1580 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1581 << "#elif defined(__GNUC__)\n"
1582 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1584 << "#define __EXTERNAL_WEAK__\n"
1587 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1588 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1589 << "#define __ATTRIBUTE_WEAK__\n"
1590 << "#elif defined(__GNUC__)\n"
1591 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1593 << "#define __ATTRIBUTE_WEAK__\n"
1596 // Add hidden visibility support. FIXME: APPLE_CC?
1597 Out << "#if defined(__GNUC__)\n"
1598 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1601 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1602 // From the GCC documentation:
1604 // double __builtin_nan (const char *str)
1606 // This is an implementation of the ISO C99 function nan.
1608 // Since ISO C99 defines this function in terms of strtod, which we do
1609 // not implement, a description of the parsing is in order. The string is
1610 // parsed as by strtol; that is, the base is recognized by leading 0 or
1611 // 0x prefixes. The number parsed is placed in the significand such that
1612 // the least significant bit of the number is at the least significant
1613 // bit of the significand. The number is truncated to fit the significand
1614 // field provided. The significand is forced to be a quiet NaN.
1616 // This function, if given a string literal, is evaluated early enough
1617 // that it is considered a compile-time constant.
1619 // float __builtin_nanf (const char *str)
1621 // Similar to __builtin_nan, except the return type is float.
1623 // double __builtin_inf (void)
1625 // Similar to __builtin_huge_val, except a warning is generated if the
1626 // target floating-point format does not support infinities. This
1627 // function is suitable for implementing the ISO C99 macro INFINITY.
1629 // float __builtin_inff (void)
1631 // Similar to __builtin_inf, except the return type is float.
1632 Out << "#ifdef __GNUC__\n"
1633 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1634 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1635 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1636 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1637 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1638 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1639 << "#define LLVM_PREFETCH(addr,rw,locality) "
1640 "__builtin_prefetch(addr,rw,locality)\n"
1641 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1642 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1643 << "#define LLVM_ASM __asm__\n"
1645 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1646 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1647 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1648 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1649 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1650 << "#define LLVM_INFF 0.0F /* Float */\n"
1651 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1652 << "#define __ATTRIBUTE_CTOR__\n"
1653 << "#define __ATTRIBUTE_DTOR__\n"
1654 << "#define LLVM_ASM(X)\n"
1657 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1658 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1659 << "#define __builtin_stack_restore(X) /* noop */\n"
1662 // Output typedefs for 128-bit integers. If these are needed with a
1663 // 32-bit target or with a C compiler that doesn't support mode(TI),
1664 // more drastic measures will be needed.
1665 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1666 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1667 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1670 // Output target-specific code that should be inserted into main.
1671 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1674 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1675 /// the StaticTors set.
1676 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1677 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1678 if (!InitList) return;
1680 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1681 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1682 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1684 if (CS->getOperand(1)->isNullValue())
1685 return; // Found a null terminator, exit printing.
1686 Constant *FP = CS->getOperand(1);
1687 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1689 FP = CE->getOperand(0);
1690 if (Function *F = dyn_cast<Function>(FP))
1691 StaticTors.insert(F);
1695 enum SpecialGlobalClass {
1697 GlobalCtors, GlobalDtors,
1701 /// getGlobalVariableClass - If this is a global that is specially recognized
1702 /// by LLVM, return a code that indicates how we should handle it.
1703 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1704 // If this is a global ctors/dtors list, handle it now.
1705 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1706 if (GV->getName() == "llvm.global_ctors")
1708 else if (GV->getName() == "llvm.global_dtors")
1712 // Otherwise, if it is other metadata, don't print it. This catches things
1713 // like debug information.
1714 if (GV->getSection() == "llvm.metadata")
1720 // PrintEscapedString - Print each character of the specified string, escaping
1721 // it if it is not printable or if it is an escape char.
1722 static void PrintEscapedString(const char *Str, unsigned Length,
1724 for (unsigned i = 0; i != Length; ++i) {
1725 unsigned char C = Str[i];
1726 if (isprint(C) && C != '\\' && C != '"')
1735 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1739 // PrintEscapedString - Print each character of the specified string, escaping
1740 // it if it is not printable or if it is an escape char.
1741 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1742 PrintEscapedString(Str.c_str(), Str.size(), Out);
1745 bool CWriter::doInitialization(Module &M) {
1746 FunctionPass::doInitialization(M);
1751 TD = new TargetData(&M);
1752 IL = new IntrinsicLowering(*TD);
1753 IL->AddPrototypes(M);
1756 std::string Triple = TheModule->getTargetTriple();
1758 Triple = llvm::sys::getHostTriple();
1761 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1762 TAsm = Match->createAsmInfo(Triple);
1764 TAsm = new CBEMCAsmInfo();
1765 TCtx = new MCContext(*TAsm, NULL);
1766 Mang = new Mangler(*TCtx, *TD);
1768 // Keep track of which functions are static ctors/dtors so they can have
1769 // an attribute added to their prototypes.
1770 std::set<Function*> StaticCtors, StaticDtors;
1771 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1773 switch (getGlobalVariableClass(I)) {
1776 FindStaticTors(I, StaticCtors);
1779 FindStaticTors(I, StaticDtors);
1784 // get declaration for alloca
1785 Out << "/* Provide Declarations */\n";
1786 Out << "#include <stdarg.h>\n"; // Varargs support
1787 Out << "#include <setjmp.h>\n"; // Unwind support
1788 Out << "#include <limits.h>\n"; // With overflow intrinsics support.
1789 generateCompilerSpecificCode(Out, TD);
1791 // Provide a definition for `bool' if not compiling with a C++ compiler.
1793 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1795 << "\n\n/* Support for floating point constants */\n"
1796 << "typedef unsigned long long ConstantDoubleTy;\n"
1797 << "typedef unsigned int ConstantFloatTy;\n"
1798 << "typedef struct { unsigned long long f1; unsigned short f2; "
1799 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1800 // This is used for both kinds of 128-bit long double; meaning differs.
1801 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1802 " ConstantFP128Ty;\n"
1803 << "\n\n/* Global Declarations */\n";
1805 // First output all the declarations for the program, because C requires
1806 // Functions & globals to be declared before they are used.
1808 if (!M.getModuleInlineAsm().empty()) {
1809 Out << "/* Module asm statements */\n"
1812 // Split the string into lines, to make it easier to read the .ll file.
1813 std::string Asm = M.getModuleInlineAsm();
1815 size_t NewLine = Asm.find_first_of('\n', CurPos);
1816 while (NewLine != std::string::npos) {
1817 // We found a newline, print the portion of the asm string from the
1818 // last newline up to this newline.
1820 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1824 NewLine = Asm.find_first_of('\n', CurPos);
1827 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1829 << "/* End Module asm statements */\n";
1832 // Loop over the symbol table, emitting all named constants...
1833 printModuleTypes(M.getTypeSymbolTable());
1835 // Global variable declarations...
1836 if (!M.global_empty()) {
1837 Out << "\n/* External Global Variable Declarations */\n";
1838 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1841 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1842 I->hasCommonLinkage())
1844 else if (I->hasDLLImportLinkage())
1845 Out << "__declspec(dllimport) ";
1847 continue; // Internal Global
1849 // Thread Local Storage
1850 if (I->isThreadLocal())
1853 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1855 if (I->hasExternalWeakLinkage())
1856 Out << " __EXTERNAL_WEAK__";
1861 // Function declarations
1862 Out << "\n/* Function Declarations */\n";
1863 Out << "double fmod(double, double);\n"; // Support for FP rem
1864 Out << "float fmodf(float, float);\n";
1865 Out << "long double fmodl(long double, long double);\n";
1867 // Store the intrinsics which will be declared/defined below.
1868 SmallVector<const Function*, 8> intrinsicsToDefine;
1870 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1871 // Don't print declarations for intrinsic functions.
1872 // Store the used intrinsics, which need to be explicitly defined.
1873 if (I->isIntrinsic()) {
1874 switch (I->getIntrinsicID()) {
1877 case Intrinsic::uadd_with_overflow:
1878 case Intrinsic::sadd_with_overflow:
1879 intrinsicsToDefine.push_back(I);
1885 if (I->getName() == "setjmp" ||
1886 I->getName() == "longjmp" || I->getName() == "_setjmp")
1889 if (I->hasExternalWeakLinkage())
1891 printFunctionSignature(I, true);
1892 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1893 Out << " __ATTRIBUTE_WEAK__";
1894 if (I->hasExternalWeakLinkage())
1895 Out << " __EXTERNAL_WEAK__";
1896 if (StaticCtors.count(I))
1897 Out << " __ATTRIBUTE_CTOR__";
1898 if (StaticDtors.count(I))
1899 Out << " __ATTRIBUTE_DTOR__";
1900 if (I->hasHiddenVisibility())
1901 Out << " __HIDDEN__";
1903 if (I->hasName() && I->getName()[0] == 1)
1904 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
1909 // Output the global variable declarations
1910 if (!M.global_empty()) {
1911 Out << "\n\n/* Global Variable Declarations */\n";
1912 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1914 if (!I->isDeclaration()) {
1915 // Ignore special globals, such as debug info.
1916 if (getGlobalVariableClass(I))
1919 if (I->hasLocalLinkage())
1924 // Thread Local Storage
1925 if (I->isThreadLocal())
1928 printType(Out, I->getType()->getElementType(), false,
1931 if (I->hasLinkOnceLinkage())
1932 Out << " __attribute__((common))";
1933 else if (I->hasCommonLinkage()) // FIXME is this right?
1934 Out << " __ATTRIBUTE_WEAK__";
1935 else if (I->hasWeakLinkage())
1936 Out << " __ATTRIBUTE_WEAK__";
1937 else if (I->hasExternalWeakLinkage())
1938 Out << " __EXTERNAL_WEAK__";
1939 if (I->hasHiddenVisibility())
1940 Out << " __HIDDEN__";
1945 // Output the global variable definitions and contents...
1946 if (!M.global_empty()) {
1947 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1948 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1950 if (!I->isDeclaration()) {
1951 // Ignore special globals, such as debug info.
1952 if (getGlobalVariableClass(I))
1955 if (I->hasLocalLinkage())
1957 else if (I->hasDLLImportLinkage())
1958 Out << "__declspec(dllimport) ";
1959 else if (I->hasDLLExportLinkage())
1960 Out << "__declspec(dllexport) ";
1962 // Thread Local Storage
1963 if (I->isThreadLocal())
1966 printType(Out, I->getType()->getElementType(), false,
1968 if (I->hasLinkOnceLinkage())
1969 Out << " __attribute__((common))";
1970 else if (I->hasWeakLinkage())
1971 Out << " __ATTRIBUTE_WEAK__";
1972 else if (I->hasCommonLinkage())
1973 Out << " __ATTRIBUTE_WEAK__";
1975 if (I->hasHiddenVisibility())
1976 Out << " __HIDDEN__";
1978 // If the initializer is not null, emit the initializer. If it is null,
1979 // we try to avoid emitting large amounts of zeros. The problem with
1980 // this, however, occurs when the variable has weak linkage. In this
1981 // case, the assembler will complain about the variable being both weak
1982 // and common, so we disable this optimization.
1983 // FIXME common linkage should avoid this problem.
1984 if (!I->getInitializer()->isNullValue()) {
1986 writeOperand(I->getInitializer(), true);
1987 } else if (I->hasWeakLinkage()) {
1988 // We have to specify an initializer, but it doesn't have to be
1989 // complete. If the value is an aggregate, print out { 0 }, and let
1990 // the compiler figure out the rest of the zeros.
1992 if (I->getInitializer()->getType()->isStructTy() ||
1993 I->getInitializer()->getType()->isVectorTy()) {
1995 } else if (I->getInitializer()->getType()->isArrayTy()) {
1996 // As with structs and vectors, but with an extra set of braces
1997 // because arrays are wrapped in structs.
2000 // Just print it out normally.
2001 writeOperand(I->getInitializer(), true);
2009 Out << "\n\n/* Function Bodies */\n";
2011 // Emit some helper functions for dealing with FCMP instruction's
2013 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
2014 Out << "return X == X && Y == Y; }\n";
2015 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
2016 Out << "return X != X || Y != Y; }\n";
2017 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
2018 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
2019 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
2020 Out << "return X != Y; }\n";
2021 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
2022 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
2023 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
2024 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
2025 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
2026 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
2027 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
2028 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
2029 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
2030 Out << "return X == Y ; }\n";
2031 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
2032 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
2033 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
2034 Out << "return X < Y ; }\n";
2035 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
2036 Out << "return X > Y ; }\n";
2037 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
2038 Out << "return X <= Y ; }\n";
2039 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
2040 Out << "return X >= Y ; }\n";
2042 // Emit definitions of the intrinsics.
2043 for (SmallVector<const Function*, 8>::const_iterator
2044 I = intrinsicsToDefine.begin(),
2045 E = intrinsicsToDefine.end(); I != E; ++I) {
2046 printIntrinsicDefinition(**I, Out);
2053 /// Output all floating point constants that cannot be printed accurately...
2054 void CWriter::printFloatingPointConstants(Function &F) {
2055 // Scan the module for floating point constants. If any FP constant is used
2056 // in the function, we want to redirect it here so that we do not depend on
2057 // the precision of the printed form, unless the printed form preserves
2060 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2062 printFloatingPointConstants(*I);
2067 void CWriter::printFloatingPointConstants(const Constant *C) {
2068 // If this is a constant expression, recursively check for constant fp values.
2069 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2070 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2071 printFloatingPointConstants(CE->getOperand(i));
2075 // Otherwise, check for a FP constant that we need to print.
2076 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2078 // Do not put in FPConstantMap if safe.
2079 isFPCSafeToPrint(FPC) ||
2080 // Already printed this constant?
2081 FPConstantMap.count(FPC))
2084 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2086 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
2087 double Val = FPC->getValueAPF().convertToDouble();
2088 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2089 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2090 << " = 0x" << utohexstr(i)
2091 << "ULL; /* " << Val << " */\n";
2092 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
2093 float Val = FPC->getValueAPF().convertToFloat();
2094 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2096 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2097 << " = 0x" << utohexstr(i)
2098 << "U; /* " << Val << " */\n";
2099 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
2100 // api needed to prevent premature destruction
2101 APInt api = FPC->getValueAPF().bitcastToAPInt();
2102 const uint64_t *p = api.getRawData();
2103 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
2104 << " = { 0x" << utohexstr(p[0])
2105 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
2106 << "}; /* Long double constant */\n";
2107 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2108 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
2109 APInt api = FPC->getValueAPF().bitcastToAPInt();
2110 const uint64_t *p = api.getRawData();
2111 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2113 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2114 << "}; /* Long double constant */\n";
2117 llvm_unreachable("Unknown float type!");
2123 /// printSymbolTable - Run through symbol table looking for type names. If a
2124 /// type name is found, emit its declaration...
2126 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2127 Out << "/* Helper union for bitcasts */\n";
2128 Out << "typedef union {\n";
2129 Out << " unsigned int Int32;\n";
2130 Out << " unsigned long long Int64;\n";
2131 Out << " float Float;\n";
2132 Out << " double Double;\n";
2133 Out << "} llvmBitCastUnion;\n";
2135 // We are only interested in the type plane of the symbol table.
2136 TypeSymbolTable::const_iterator I = TST.begin();
2137 TypeSymbolTable::const_iterator End = TST.end();
2139 // If there are no type names, exit early.
2140 if (I == End) return;
2142 // Print out forward declarations for structure types before anything else!
2143 Out << "/* Structure forward decls */\n";
2144 for (; I != End; ++I) {
2145 std::string Name = "struct " + CBEMangle("l_"+I->first);
2146 Out << Name << ";\n";
2147 TypeNames.insert(std::make_pair(I->second, Name));
2152 // Now we can print out typedefs. Above, we guaranteed that this can only be
2153 // for struct or opaque types.
2154 Out << "/* Typedefs */\n";
2155 for (I = TST.begin(); I != End; ++I) {
2156 std::string Name = CBEMangle("l_"+I->first);
2158 printType(Out, I->second, false, Name);
2164 // Keep track of which structures have been printed so far...
2165 std::set<const Type *> StructPrinted;
2167 // Loop over all structures then push them into the stack so they are
2168 // printed in the correct order.
2170 Out << "/* Structure contents */\n";
2171 for (I = TST.begin(); I != End; ++I)
2172 if (I->second->isStructTy() || I->second->isArrayTy())
2173 // Only print out used types!
2174 printContainedStructs(I->second, StructPrinted);
2177 // Push the struct onto the stack and recursively push all structs
2178 // this one depends on.
2180 // TODO: Make this work properly with vector types
2182 void CWriter::printContainedStructs(const Type *Ty,
2183 std::set<const Type*> &StructPrinted) {
2184 // Don't walk through pointers.
2185 if (Ty->isPointerTy() || Ty->isPrimitiveType() || Ty->isIntegerTy())
2188 // Print all contained types first.
2189 for (Type::subtype_iterator I = Ty->subtype_begin(),
2190 E = Ty->subtype_end(); I != E; ++I)
2191 printContainedStructs(*I, StructPrinted);
2193 if (Ty->isStructTy() || Ty->isArrayTy()) {
2194 // Check to see if we have already printed this struct.
2195 if (StructPrinted.insert(Ty).second) {
2196 // Print structure type out.
2197 std::string Name = TypeNames[Ty];
2198 printType(Out, Ty, false, Name, true);
2204 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2205 /// isStructReturn - Should this function actually return a struct by-value?
2206 bool isStructReturn = F->hasStructRetAttr();
2208 if (F->hasLocalLinkage()) Out << "static ";
2209 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2210 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2211 switch (F->getCallingConv()) {
2212 case CallingConv::X86_StdCall:
2213 Out << "__attribute__((stdcall)) ";
2215 case CallingConv::X86_FastCall:
2216 Out << "__attribute__((fastcall)) ";
2218 case CallingConv::X86_ThisCall:
2219 Out << "__attribute__((thiscall)) ";
2225 // Loop over the arguments, printing them...
2226 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
2227 const AttrListPtr &PAL = F->getAttributes();
2230 raw_string_ostream FunctionInnards(tstr);
2232 // Print out the name...
2233 FunctionInnards << GetValueName(F) << '(';
2235 bool PrintedArg = false;
2236 if (!F->isDeclaration()) {
2237 if (!F->arg_empty()) {
2238 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2241 // If this is a struct-return function, don't print the hidden
2242 // struct-return argument.
2243 if (isStructReturn) {
2244 assert(I != E && "Invalid struct return function!");
2249 std::string ArgName;
2250 for (; I != E; ++I) {
2251 if (PrintedArg) FunctionInnards << ", ";
2252 if (I->hasName() || !Prototype)
2253 ArgName = GetValueName(I);
2256 const Type *ArgTy = I->getType();
2257 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2258 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2259 ByValParams.insert(I);
2261 printType(FunctionInnards, ArgTy,
2262 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
2269 // Loop over the arguments, printing them.
2270 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
2273 // If this is a struct-return function, don't print the hidden
2274 // struct-return argument.
2275 if (isStructReturn) {
2276 assert(I != E && "Invalid struct return function!");
2281 for (; I != E; ++I) {
2282 if (PrintedArg) FunctionInnards << ", ";
2283 const Type *ArgTy = *I;
2284 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2285 assert(ArgTy->isPointerTy());
2286 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2288 printType(FunctionInnards, ArgTy,
2289 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
2295 if (!PrintedArg && FT->isVarArg()) {
2296 FunctionInnards << "int vararg_dummy_arg";
2300 // Finish printing arguments... if this is a vararg function, print the ...,
2301 // unless there are no known types, in which case, we just emit ().
2303 if (FT->isVarArg() && PrintedArg) {
2304 FunctionInnards << ",..."; // Output varargs portion of signature!
2305 } else if (!FT->isVarArg() && !PrintedArg) {
2306 FunctionInnards << "void"; // ret() -> ret(void) in C.
2308 FunctionInnards << ')';
2310 // Get the return tpe for the function.
2312 if (!isStructReturn)
2313 RetTy = F->getReturnType();
2315 // If this is a struct-return function, print the struct-return type.
2316 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2319 // Print out the return type and the signature built above.
2320 printType(Out, RetTy,
2321 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
2322 FunctionInnards.str());
2325 static inline bool isFPIntBitCast(const Instruction &I) {
2326 if (!isa<BitCastInst>(I))
2328 const Type *SrcTy = I.getOperand(0)->getType();
2329 const Type *DstTy = I.getType();
2330 return (SrcTy->isFloatingPointTy() && DstTy->isIntegerTy()) ||
2331 (DstTy->isFloatingPointTy() && SrcTy->isIntegerTy());
2334 void CWriter::printFunction(Function &F) {
2335 /// isStructReturn - Should this function actually return a struct by-value?
2336 bool isStructReturn = F.hasStructRetAttr();
2338 printFunctionSignature(&F, false);
2341 // If this is a struct return function, handle the result with magic.
2342 if (isStructReturn) {
2343 const Type *StructTy =
2344 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2346 printType(Out, StructTy, false, "StructReturn");
2347 Out << "; /* Struct return temporary */\n";
2350 printType(Out, F.arg_begin()->getType(), false,
2351 GetValueName(F.arg_begin()));
2352 Out << " = &StructReturn;\n";
2355 bool PrintedVar = false;
2357 // print local variable information for the function
2358 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2359 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2361 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2362 Out << "; /* Address-exposed local */\n";
2364 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2365 !isInlinableInst(*I)) {
2367 printType(Out, I->getType(), false, GetValueName(&*I));
2370 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2372 printType(Out, I->getType(), false,
2373 GetValueName(&*I)+"__PHI_TEMPORARY");
2378 // We need a temporary for the BitCast to use so it can pluck a value out
2379 // of a union to do the BitCast. This is separate from the need for a
2380 // variable to hold the result of the BitCast.
2381 if (isFPIntBitCast(*I)) {
2382 Out << " llvmBitCastUnion " << GetValueName(&*I)
2383 << "__BITCAST_TEMPORARY;\n";
2391 if (F.hasExternalLinkage() && F.getName() == "main")
2392 Out << " CODE_FOR_MAIN();\n";
2394 // print the basic blocks
2395 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2396 if (Loop *L = LI->getLoopFor(BB)) {
2397 if (L->getHeader() == BB && L->getParentLoop() == 0)
2400 printBasicBlock(BB);
2407 void CWriter::printLoop(Loop *L) {
2408 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2409 << "' to make GCC happy */\n";
2410 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2411 BasicBlock *BB = L->getBlocks()[i];
2412 Loop *BBLoop = LI->getLoopFor(BB);
2414 printBasicBlock(BB);
2415 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2418 Out << " } while (1); /* end of syntactic loop '"
2419 << L->getHeader()->getName() << "' */\n";
2422 void CWriter::printBasicBlock(BasicBlock *BB) {
2424 // Don't print the label for the basic block if there are no uses, or if
2425 // the only terminator use is the predecessor basic block's terminator.
2426 // We have to scan the use list because PHI nodes use basic blocks too but
2427 // do not require a label to be generated.
2429 bool NeedsLabel = false;
2430 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2431 if (isGotoCodeNecessary(*PI, BB)) {
2436 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2438 // Output all of the instructions in the basic block...
2439 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2441 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2442 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2447 writeInstComputationInline(*II);
2452 // Don't emit prefix or suffix for the terminator.
2453 visit(*BB->getTerminator());
2457 // Specific Instruction type classes... note that all of the casts are
2458 // necessary because we use the instruction classes as opaque types...
2460 void CWriter::visitReturnInst(ReturnInst &I) {
2461 // If this is a struct return function, return the temporary struct.
2462 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
2464 if (isStructReturn) {
2465 Out << " return StructReturn;\n";
2469 // Don't output a void return if this is the last basic block in the function
2470 if (I.getNumOperands() == 0 &&
2471 &*--I.getParent()->getParent()->end() == I.getParent() &&
2472 !I.getParent()->size() == 1) {
2477 if (I.getNumOperands()) {
2479 writeOperand(I.getOperand(0));
2484 void CWriter::visitSwitchInst(SwitchInst &SI) {
2487 writeOperand(SI.getOperand(0));
2488 Out << ") {\n default:\n";
2489 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2490 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2492 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2494 writeOperand(SI.getOperand(i));
2496 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2497 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2498 printBranchToBlock(SI.getParent(), Succ, 2);
2499 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
2505 void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
2506 Out << " goto *(void*)(";
2507 writeOperand(IBI.getOperand(0));
2511 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2512 Out << " /*UNREACHABLE*/;\n";
2515 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2516 /// FIXME: This should be reenabled, but loop reordering safe!!
2519 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
2520 return true; // Not the direct successor, we need a goto.
2522 //isa<SwitchInst>(From->getTerminator())
2524 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2529 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2530 BasicBlock *Successor,
2532 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2533 PHINode *PN = cast<PHINode>(I);
2534 // Now we have to do the printing.
2535 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2536 if (!isa<UndefValue>(IV)) {
2537 Out << std::string(Indent, ' ');
2538 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2540 Out << "; /* for PHI node */\n";
2545 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2547 if (isGotoCodeNecessary(CurBB, Succ)) {
2548 Out << std::string(Indent, ' ') << " goto ";
2554 // Branch instruction printing - Avoid printing out a branch to a basic block
2555 // that immediately succeeds the current one.
2557 void CWriter::visitBranchInst(BranchInst &I) {
2559 if (I.isConditional()) {
2560 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2562 writeOperand(I.getCondition());
2565 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2566 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2568 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2569 Out << " } else {\n";
2570 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2571 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2574 // First goto not necessary, assume second one is...
2576 writeOperand(I.getCondition());
2579 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2580 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2585 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2586 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2591 // PHI nodes get copied into temporary values at the end of predecessor basic
2592 // blocks. We now need to copy these temporary values into the REAL value for
2594 void CWriter::visitPHINode(PHINode &I) {
2596 Out << "__PHI_TEMPORARY";
2600 void CWriter::visitBinaryOperator(Instruction &I) {
2601 // binary instructions, shift instructions, setCond instructions.
2602 assert(!I.getType()->isPointerTy());
2604 // We must cast the results of binary operations which might be promoted.
2605 bool needsCast = false;
2606 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2607 (I.getType() == Type::getInt16Ty(I.getContext()))
2608 || (I.getType() == Type::getFloatTy(I.getContext()))) {
2611 printType(Out, I.getType(), false);
2615 // If this is a negation operation, print it out as such. For FP, we don't
2616 // want to print "-0.0 - X".
2617 if (BinaryOperator::isNeg(&I)) {
2619 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2621 } else if (BinaryOperator::isFNeg(&I)) {
2623 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2625 } else if (I.getOpcode() == Instruction::FRem) {
2626 // Output a call to fmod/fmodf instead of emitting a%b
2627 if (I.getType() == Type::getFloatTy(I.getContext()))
2629 else if (I.getType() == Type::getDoubleTy(I.getContext()))
2631 else // all 3 flavors of long double
2633 writeOperand(I.getOperand(0));
2635 writeOperand(I.getOperand(1));
2639 // Write out the cast of the instruction's value back to the proper type
2641 bool NeedsClosingParens = writeInstructionCast(I);
2643 // Certain instructions require the operand to be forced to a specific type
2644 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2645 // below for operand 1
2646 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2648 switch (I.getOpcode()) {
2649 case Instruction::Add:
2650 case Instruction::FAdd: Out << " + "; break;
2651 case Instruction::Sub:
2652 case Instruction::FSub: Out << " - "; break;
2653 case Instruction::Mul:
2654 case Instruction::FMul: Out << " * "; break;
2655 case Instruction::URem:
2656 case Instruction::SRem:
2657 case Instruction::FRem: Out << " % "; break;
2658 case Instruction::UDiv:
2659 case Instruction::SDiv:
2660 case Instruction::FDiv: Out << " / "; break;
2661 case Instruction::And: Out << " & "; break;
2662 case Instruction::Or: Out << " | "; break;
2663 case Instruction::Xor: Out << " ^ "; break;
2664 case Instruction::Shl : Out << " << "; break;
2665 case Instruction::LShr:
2666 case Instruction::AShr: Out << " >> "; break;
2669 errs() << "Invalid operator type!" << I;
2671 llvm_unreachable(0);
2674 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2675 if (NeedsClosingParens)
2684 void CWriter::visitICmpInst(ICmpInst &I) {
2685 // We must cast the results of icmp which might be promoted.
2686 bool needsCast = false;
2688 // Write out the cast of the instruction's value back to the proper type
2690 bool NeedsClosingParens = writeInstructionCast(I);
2692 // Certain icmp predicate require the operand to be forced to a specific type
2693 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2694 // below for operand 1
2695 writeOperandWithCast(I.getOperand(0), I);
2697 switch (I.getPredicate()) {
2698 case ICmpInst::ICMP_EQ: Out << " == "; break;
2699 case ICmpInst::ICMP_NE: Out << " != "; break;
2700 case ICmpInst::ICMP_ULE:
2701 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2702 case ICmpInst::ICMP_UGE:
2703 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2704 case ICmpInst::ICMP_ULT:
2705 case ICmpInst::ICMP_SLT: Out << " < "; break;
2706 case ICmpInst::ICMP_UGT:
2707 case ICmpInst::ICMP_SGT: Out << " > "; break;
2710 errs() << "Invalid icmp predicate!" << I;
2712 llvm_unreachable(0);
2715 writeOperandWithCast(I.getOperand(1), I);
2716 if (NeedsClosingParens)
2724 void CWriter::visitFCmpInst(FCmpInst &I) {
2725 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2729 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2735 switch (I.getPredicate()) {
2736 default: llvm_unreachable("Illegal FCmp predicate");
2737 case FCmpInst::FCMP_ORD: op = "ord"; break;
2738 case FCmpInst::FCMP_UNO: op = "uno"; break;
2739 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2740 case FCmpInst::FCMP_UNE: op = "une"; break;
2741 case FCmpInst::FCMP_ULT: op = "ult"; break;
2742 case FCmpInst::FCMP_ULE: op = "ule"; break;
2743 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2744 case FCmpInst::FCMP_UGE: op = "uge"; break;
2745 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2746 case FCmpInst::FCMP_ONE: op = "one"; break;
2747 case FCmpInst::FCMP_OLT: op = "olt"; break;
2748 case FCmpInst::FCMP_OLE: op = "ole"; break;
2749 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2750 case FCmpInst::FCMP_OGE: op = "oge"; break;
2753 Out << "llvm_fcmp_" << op << "(";
2754 // Write the first operand
2755 writeOperand(I.getOperand(0));
2757 // Write the second operand
2758 writeOperand(I.getOperand(1));
2762 static const char * getFloatBitCastField(const Type *Ty) {
2763 switch (Ty->getTypeID()) {
2764 default: llvm_unreachable("Invalid Type");
2765 case Type::FloatTyID: return "Float";
2766 case Type::DoubleTyID: return "Double";
2767 case Type::IntegerTyID: {
2768 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2777 void CWriter::visitCastInst(CastInst &I) {
2778 const Type *DstTy = I.getType();
2779 const Type *SrcTy = I.getOperand(0)->getType();
2780 if (isFPIntBitCast(I)) {
2782 // These int<->float and long<->double casts need to be handled specially
2783 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2784 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2785 writeOperand(I.getOperand(0));
2786 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2787 << getFloatBitCastField(I.getType());
2793 printCast(I.getOpcode(), SrcTy, DstTy);
2795 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2796 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2797 I.getOpcode() == Instruction::SExt)
2800 writeOperand(I.getOperand(0));
2802 if (DstTy == Type::getInt1Ty(I.getContext()) &&
2803 (I.getOpcode() == Instruction::Trunc ||
2804 I.getOpcode() == Instruction::FPToUI ||
2805 I.getOpcode() == Instruction::FPToSI ||
2806 I.getOpcode() == Instruction::PtrToInt)) {
2807 // Make sure we really get a trunc to bool by anding the operand with 1
2813 void CWriter::visitSelectInst(SelectInst &I) {
2815 writeOperand(I.getCondition());
2817 writeOperand(I.getTrueValue());
2819 writeOperand(I.getFalseValue());
2823 // Returns the macro name or value of the max or min of an integer type
2824 // (as defined in limits.h).
2825 static void printLimitValue(const IntegerType &Ty, bool isSigned, bool isMax,
2828 const char* sprefix = "";
2830 unsigned NumBits = Ty.getBitWidth();
2834 } else if (NumBits <= 16) {
2836 } else if (NumBits <= 32) {
2838 } else if (NumBits <= 64) {
2841 llvm_unreachable("Bit widths > 64 not implemented yet");
2845 Out << sprefix << type << (isMax ? "_MAX" : "_MIN");
2847 Out << "U" << type << (isMax ? "_MAX" : "0");
2850 static bool isSupportedIntegerSize(const IntegerType &T) {
2851 return T.getBitWidth() == 8 || T.getBitWidth() == 16 ||
2852 T.getBitWidth() == 32 || T.getBitWidth() == 64;
2855 void CWriter::printIntrinsicDefinition(const Function &F, raw_ostream &Out) {
2856 const FunctionType *funT = F.getFunctionType();
2857 const Type *retT = F.getReturnType();
2858 const IntegerType *elemT = cast<IntegerType>(funT->getParamType(1));
2860 assert(isSupportedIntegerSize(*elemT) &&
2861 "CBackend does not support arbitrary size integers.");
2862 assert(cast<StructType>(retT)->getElementType(0) == elemT &&
2863 elemT == funT->getParamType(0) && funT->getNumParams() == 2);
2865 switch (F.getIntrinsicID()) {
2867 llvm_unreachable("Unsupported Intrinsic.");
2868 case Intrinsic::uadd_with_overflow:
2869 // static inline Rty uadd_ixx(unsigned ixx a, unsigned ixx b) {
2871 // r.field0 = a + b;
2872 // r.field1 = (r.field0 < a);
2875 Out << "static inline ";
2876 printType(Out, retT);
2877 Out << GetValueName(&F);
2879 printSimpleType(Out, elemT, false);
2881 printSimpleType(Out, elemT, false);
2883 printType(Out, retT);
2885 Out << " r.field0 = a + b;\n";
2886 Out << " r.field1 = (r.field0 < a);\n";
2887 Out << " return r;\n}\n";
2890 case Intrinsic::sadd_with_overflow:
2891 // static inline Rty sadd_ixx(ixx a, ixx b) {
2893 // r.field1 = (b > 0 && a > XX_MAX - b) ||
2894 // (b < 0 && a < XX_MIN - b);
2895 // r.field0 = r.field1 ? 0 : a + b;
2899 printType(Out, retT);
2900 Out << GetValueName(&F);
2902 printSimpleType(Out, elemT, true);
2904 printSimpleType(Out, elemT, true);
2906 printType(Out, retT);
2908 Out << " r.field1 = (b > 0 && a > ";
2909 printLimitValue(*elemT, true, true, Out);
2910 Out << " - b) || (b < 0 && a < ";
2911 printLimitValue(*elemT, true, false, Out);
2913 Out << " r.field0 = r.field1 ? 0 : a + b;\n";
2914 Out << " return r;\n}\n";
2919 void CWriter::lowerIntrinsics(Function &F) {
2920 // This is used to keep track of intrinsics that get generated to a lowered
2921 // function. We must generate the prototypes before the function body which
2922 // will only be expanded on first use (by the loop below).
2923 std::vector<Function*> prototypesToGen;
2925 // Examine all the instructions in this function to find the intrinsics that
2926 // need to be lowered.
2927 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2928 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2929 if (CallInst *CI = dyn_cast<CallInst>(I++))
2930 if (Function *F = CI->getCalledFunction())
2931 switch (F->getIntrinsicID()) {
2932 case Intrinsic::not_intrinsic:
2933 case Intrinsic::memory_barrier:
2934 case Intrinsic::vastart:
2935 case Intrinsic::vacopy:
2936 case Intrinsic::vaend:
2937 case Intrinsic::returnaddress:
2938 case Intrinsic::frameaddress:
2939 case Intrinsic::setjmp:
2940 case Intrinsic::longjmp:
2941 case Intrinsic::prefetch:
2942 case Intrinsic::powi:
2943 case Intrinsic::x86_sse_cmp_ss:
2944 case Intrinsic::x86_sse_cmp_ps:
2945 case Intrinsic::x86_sse2_cmp_sd:
2946 case Intrinsic::x86_sse2_cmp_pd:
2947 case Intrinsic::ppc_altivec_lvsl:
2948 case Intrinsic::uadd_with_overflow:
2949 case Intrinsic::sadd_with_overflow:
2950 // We directly implement these intrinsics
2953 // If this is an intrinsic that directly corresponds to a GCC
2954 // builtin, we handle it.
2955 const char *BuiltinName = "";
2956 #define GET_GCC_BUILTIN_NAME
2957 #include "llvm/Intrinsics.gen"
2958 #undef GET_GCC_BUILTIN_NAME
2959 // If we handle it, don't lower it.
2960 if (BuiltinName[0]) break;
2962 // All other intrinsic calls we must lower.
2963 Instruction *Before = 0;
2964 if (CI != &BB->front())
2965 Before = prior(BasicBlock::iterator(CI));
2967 IL->LowerIntrinsicCall(CI);
2968 if (Before) { // Move iterator to instruction after call
2973 // If the intrinsic got lowered to another call, and that call has
2974 // a definition then we need to make sure its prototype is emitted
2975 // before any calls to it.
2976 if (CallInst *Call = dyn_cast<CallInst>(I))
2977 if (Function *NewF = Call->getCalledFunction())
2978 if (!NewF->isDeclaration())
2979 prototypesToGen.push_back(NewF);
2984 // We may have collected some prototypes to emit in the loop above.
2985 // Emit them now, before the function that uses them is emitted. But,
2986 // be careful not to emit them twice.
2987 std::vector<Function*>::iterator I = prototypesToGen.begin();
2988 std::vector<Function*>::iterator E = prototypesToGen.end();
2989 for ( ; I != E; ++I) {
2990 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2992 printFunctionSignature(*I, true);
2998 void CWriter::visitCallInst(CallInst &I) {
2999 if (isa<InlineAsm>(I.getCalledValue()))
3000 return visitInlineAsm(I);
3002 bool WroteCallee = false;
3004 // Handle intrinsic function calls first...
3005 if (Function *F = I.getCalledFunction())
3006 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3007 if (visitBuiltinCall(I, ID, WroteCallee))
3010 Value *Callee = I.getCalledValue();
3012 const PointerType *PTy = cast<PointerType>(Callee->getType());
3013 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3015 // If this is a call to a struct-return function, assign to the first
3016 // parameter instead of passing it to the call.
3017 const AttrListPtr &PAL = I.getAttributes();
3018 bool hasByVal = I.hasByValArgument();
3019 bool isStructRet = I.hasStructRetAttr();
3021 writeOperandDeref(I.getArgOperand(0));
3025 if (I.isTailCall()) Out << " /*tail*/ ";
3028 // If this is an indirect call to a struct return function, we need to cast
3029 // the pointer. Ditto for indirect calls with byval arguments.
3030 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
3032 // GCC is a real PITA. It does not permit codegening casts of functions to
3033 // function pointers if they are in a call (it generates a trap instruction
3034 // instead!). We work around this by inserting a cast to void* in between
3035 // the function and the function pointer cast. Unfortunately, we can't just
3036 // form the constant expression here, because the folder will immediately
3039 // Note finally, that this is completely unsafe. ANSI C does not guarantee
3040 // that void* and function pointers have the same size. :( To deal with this
3041 // in the common case, we handle casts where the number of arguments passed
3044 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
3046 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
3052 // Ok, just cast the pointer type.
3055 printStructReturnPointerFunctionType(Out, PAL,
3056 cast<PointerType>(I.getCalledValue()->getType()));
3058 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
3060 printType(Out, I.getCalledValue()->getType());
3063 writeOperand(Callee);
3064 if (NeedsCast) Out << ')';
3069 bool PrintedArg = false;
3070 if(FTy->isVarArg() && !FTy->getNumParams()) {
3071 Out << "0 /*dummy arg*/";
3075 unsigned NumDeclaredParams = FTy->getNumParams();
3077 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
3079 if (isStructRet) { // Skip struct return argument.
3085 for (; AI != AE; ++AI, ++ArgNo) {
3086 if (PrintedArg) Out << ", ";
3087 if (ArgNo < NumDeclaredParams &&
3088 (*AI)->getType() != FTy->getParamType(ArgNo)) {
3090 printType(Out, FTy->getParamType(ArgNo),
3091 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
3094 // Check if the argument is expected to be passed by value.
3095 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
3096 writeOperandDeref(*AI);
3104 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
3105 /// if the entire call is handled, return false if it wasn't handled, and
3106 /// optionally set 'WroteCallee' if the callee has already been printed out.
3107 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
3108 bool &WroteCallee) {
3111 // If this is an intrinsic that directly corresponds to a GCC
3112 // builtin, we emit it here.
3113 const char *BuiltinName = "";
3114 Function *F = I.getCalledFunction();
3115 #define GET_GCC_BUILTIN_NAME
3116 #include "llvm/Intrinsics.gen"
3117 #undef GET_GCC_BUILTIN_NAME
3118 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
3124 case Intrinsic::memory_barrier:
3125 Out << "__sync_synchronize()";
3127 case Intrinsic::vastart:
3130 Out << "va_start(*(va_list*)";
3131 writeOperand(I.getArgOperand(0));
3133 // Output the last argument to the enclosing function.
3134 if (I.getParent()->getParent()->arg_empty())
3135 Out << "vararg_dummy_arg";
3137 writeOperand(--I.getParent()->getParent()->arg_end());
3140 case Intrinsic::vaend:
3141 if (!isa<ConstantPointerNull>(I.getArgOperand(0))) {
3142 Out << "0; va_end(*(va_list*)";
3143 writeOperand(I.getArgOperand(0));
3146 Out << "va_end(*(va_list*)0)";
3149 case Intrinsic::vacopy:
3151 Out << "va_copy(*(va_list*)";
3152 writeOperand(I.getArgOperand(0));
3153 Out << ", *(va_list*)";
3154 writeOperand(I.getArgOperand(1));
3157 case Intrinsic::returnaddress:
3158 Out << "__builtin_return_address(";
3159 writeOperand(I.getArgOperand(0));
3162 case Intrinsic::frameaddress:
3163 Out << "__builtin_frame_address(";
3164 writeOperand(I.getArgOperand(0));
3167 case Intrinsic::powi:
3168 Out << "__builtin_powi(";
3169 writeOperand(I.getArgOperand(0));
3171 writeOperand(I.getArgOperand(1));
3174 case Intrinsic::setjmp:
3175 Out << "setjmp(*(jmp_buf*)";
3176 writeOperand(I.getArgOperand(0));
3179 case Intrinsic::longjmp:
3180 Out << "longjmp(*(jmp_buf*)";
3181 writeOperand(I.getArgOperand(0));
3183 writeOperand(I.getArgOperand(1));
3186 case Intrinsic::prefetch:
3187 Out << "LLVM_PREFETCH((const void *)";
3188 writeOperand(I.getArgOperand(0));
3190 writeOperand(I.getArgOperand(1));
3192 writeOperand(I.getArgOperand(2));
3195 case Intrinsic::stacksave:
3196 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3197 // to work around GCC bugs (see PR1809).
3198 Out << "0; *((void**)&" << GetValueName(&I)
3199 << ") = __builtin_stack_save()";
3201 case Intrinsic::x86_sse_cmp_ss:
3202 case Intrinsic::x86_sse_cmp_ps:
3203 case Intrinsic::x86_sse2_cmp_sd:
3204 case Intrinsic::x86_sse2_cmp_pd:
3206 printType(Out, I.getType());
3208 // Multiple GCC builtins multiplex onto this intrinsic.
3209 switch (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()) {
3210 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
3211 case 0: Out << "__builtin_ia32_cmpeq"; break;
3212 case 1: Out << "__builtin_ia32_cmplt"; break;
3213 case 2: Out << "__builtin_ia32_cmple"; break;
3214 case 3: Out << "__builtin_ia32_cmpunord"; break;
3215 case 4: Out << "__builtin_ia32_cmpneq"; break;
3216 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3217 case 6: Out << "__builtin_ia32_cmpnle"; break;
3218 case 7: Out << "__builtin_ia32_cmpord"; break;
3220 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3224 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3230 writeOperand(I.getArgOperand(0));
3232 writeOperand(I.getArgOperand(1));
3235 case Intrinsic::ppc_altivec_lvsl:
3237 printType(Out, I.getType());
3239 Out << "__builtin_altivec_lvsl(0, (void*)";
3240 writeOperand(I.getArgOperand(0));
3243 case Intrinsic::uadd_with_overflow:
3244 case Intrinsic::sadd_with_overflow:
3245 Out << GetValueName(I.getCalledFunction()) << "(";
3246 writeOperand(I.getArgOperand(0));
3248 writeOperand(I.getArgOperand(1));
3254 //This converts the llvm constraint string to something gcc is expecting.
3255 //TODO: work out platform independent constraints and factor those out
3256 // of the per target tables
3257 // handle multiple constraint codes
3258 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
3259 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3261 // Grab the translation table from MCAsmInfo if it exists.
3262 const MCAsmInfo *TargetAsm;
3263 std::string Triple = TheModule->getTargetTriple();
3265 Triple = llvm::sys::getHostTriple();
3268 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3269 TargetAsm = Match->createAsmInfo(Triple);
3273 const char *const *table = TargetAsm->getAsmCBE();
3275 // Search the translation table if it exists.
3276 for (int i = 0; table && table[i]; i += 2)
3277 if (c.Codes[0] == table[i]) {
3282 // Default is identity.
3287 //TODO: import logic from AsmPrinter.cpp
3288 static std::string gccifyAsm(std::string asmstr) {
3289 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3290 if (asmstr[i] == '\n')
3291 asmstr.replace(i, 1, "\\n");
3292 else if (asmstr[i] == '\t')
3293 asmstr.replace(i, 1, "\\t");
3294 else if (asmstr[i] == '$') {
3295 if (asmstr[i + 1] == '{') {
3296 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3297 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3298 std::string n = "%" +
3299 asmstr.substr(a + 1, b - a - 1) +
3300 asmstr.substr(i + 2, a - i - 2);
3301 asmstr.replace(i, b - i + 1, n);
3304 asmstr.replace(i, 1, "%");
3306 else if (asmstr[i] == '%')//grr
3307 { asmstr.replace(i, 1, "%%"); ++i;}
3312 //TODO: assumptions about what consume arguments from the call are likely wrong
3313 // handle communitivity
3314 void CWriter::visitInlineAsm(CallInst &CI) {
3315 InlineAsm* as = cast<InlineAsm>(CI.getCalledValue());
3316 InlineAsm::ConstraintInfoVector Constraints = as->ParseConstraints();
3318 std::vector<std::pair<Value*, int> > ResultVals;
3319 if (CI.getType() == Type::getVoidTy(CI.getContext()))
3321 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3322 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3323 ResultVals.push_back(std::make_pair(&CI, (int)i));
3325 ResultVals.push_back(std::make_pair(&CI, -1));
3328 // Fix up the asm string for gcc and emit it.
3329 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3332 unsigned ValueCount = 0;
3333 bool IsFirst = true;
3335 // Convert over all the output constraints.
3336 for (InlineAsm::ConstraintInfoVector::iterator I = Constraints.begin(),
3337 E = Constraints.end(); I != E; ++I) {
3339 if (I->Type != InlineAsm::isOutput) {
3341 continue; // Ignore non-output constraints.
3344 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3345 std::string C = InterpretASMConstraint(*I);
3346 if (C.empty()) continue;
3357 if (ValueCount < ResultVals.size()) {
3358 DestVal = ResultVals[ValueCount].first;
3359 DestValNo = ResultVals[ValueCount].second;
3361 DestVal = CI.getArgOperand(ValueCount-ResultVals.size());
3363 if (I->isEarlyClobber)
3366 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3367 if (DestValNo != -1)
3368 Out << ".field" << DestValNo; // Multiple retvals.
3374 // Convert over all the input constraints.
3378 for (InlineAsm::ConstraintInfoVector::iterator I = Constraints.begin(),
3379 E = Constraints.end(); I != E; ++I) {
3380 if (I->Type != InlineAsm::isInput) {
3382 continue; // Ignore non-input constraints.
3385 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3386 std::string C = InterpretASMConstraint(*I);
3387 if (C.empty()) continue;
3394 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3395 Value *SrcVal = CI.getArgOperand(ValueCount-ResultVals.size());
3397 Out << "\"" << C << "\"(";
3399 writeOperand(SrcVal);
3401 writeOperandDeref(SrcVal);
3405 // Convert over the clobber constraints.
3407 for (InlineAsm::ConstraintInfoVector::iterator I = Constraints.begin(),
3408 E = Constraints.end(); I != E; ++I) {
3409 if (I->Type != InlineAsm::isClobber)
3410 continue; // Ignore non-input constraints.
3412 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3413 std::string C = InterpretASMConstraint(*I);
3414 if (C.empty()) continue;
3421 Out << '\"' << C << '"';
3427 void CWriter::visitAllocaInst(AllocaInst &I) {
3429 printType(Out, I.getType());
3430 Out << ") alloca(sizeof(";
3431 printType(Out, I.getType()->getElementType());
3433 if (I.isArrayAllocation()) {
3435 writeOperand(I.getOperand(0));
3440 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
3441 gep_type_iterator E, bool Static) {
3443 // If there are no indices, just print out the pointer.
3449 // Find out if the last index is into a vector. If so, we have to print this
3450 // specially. Since vectors can't have elements of indexable type, only the
3451 // last index could possibly be of a vector element.
3452 const VectorType *LastIndexIsVector = 0;
3454 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3455 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
3460 // If the last index is into a vector, we can't print it as &a[i][j] because
3461 // we can't index into a vector with j in GCC. Instead, emit this as
3462 // (((float*)&a[i])+j)
3463 if (LastIndexIsVector) {
3465 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3471 // If the first index is 0 (very typical) we can do a number of
3472 // simplifications to clean up the code.
3473 Value *FirstOp = I.getOperand();
3474 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3475 // First index isn't simple, print it the hard way.
3478 ++I; // Skip the zero index.
3480 // Okay, emit the first operand. If Ptr is something that is already address
3481 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3482 if (isAddressExposed(Ptr)) {
3483 writeOperandInternal(Ptr, Static);
3484 } else if (I != E && (*I)->isStructTy()) {
3485 // If we didn't already emit the first operand, see if we can print it as
3486 // P->f instead of "P[0].f"
3488 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3489 ++I; // eat the struct index as well.
3491 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3498 for (; I != E; ++I) {
3499 if ((*I)->isStructTy()) {
3500 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3501 } else if ((*I)->isArrayTy()) {
3503 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3505 } else if (!(*I)->isVectorTy()) {
3507 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3510 // If the last index is into a vector, then print it out as "+j)". This
3511 // works with the 'LastIndexIsVector' code above.
3512 if (isa<Constant>(I.getOperand()) &&
3513 cast<Constant>(I.getOperand())->isNullValue()) {
3514 Out << "))"; // avoid "+0".
3517 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3525 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3526 bool IsVolatile, unsigned Alignment) {
3528 bool IsUnaligned = Alignment &&
3529 Alignment < TD->getABITypeAlignment(OperandType);
3533 if (IsVolatile || IsUnaligned) {
3536 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3537 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3540 if (IsVolatile) Out << "volatile ";
3546 writeOperand(Operand);
3548 if (IsVolatile || IsUnaligned) {
3555 void CWriter::visitLoadInst(LoadInst &I) {
3556 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3561 void CWriter::visitStoreInst(StoreInst &I) {
3562 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3563 I.isVolatile(), I.getAlignment());
3565 Value *Operand = I.getOperand(0);
3566 Constant *BitMask = 0;
3567 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3568 if (!ITy->isPowerOf2ByteWidth())
3569 // We have a bit width that doesn't match an even power-of-2 byte
3570 // size. Consequently we must & the value with the type's bit mask
3571 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
3574 writeOperand(Operand);
3577 printConstant(BitMask, false);
3582 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3583 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
3584 gep_type_end(I), false);
3587 void CWriter::visitVAArgInst(VAArgInst &I) {
3588 Out << "va_arg(*(va_list*)";
3589 writeOperand(I.getOperand(0));
3591 printType(Out, I.getType());
3595 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3596 const Type *EltTy = I.getType()->getElementType();
3597 writeOperand(I.getOperand(0));
3600 printType(Out, PointerType::getUnqual(EltTy));
3601 Out << ")(&" << GetValueName(&I) << "))[";
3602 writeOperand(I.getOperand(2));
3604 writeOperand(I.getOperand(1));
3608 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3609 // We know that our operand is not inlined.
3612 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3613 printType(Out, PointerType::getUnqual(EltTy));
3614 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3615 writeOperand(I.getOperand(1));
3619 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3621 printType(Out, SVI.getType());
3623 const VectorType *VT = SVI.getType();
3624 unsigned NumElts = VT->getNumElements();
3625 const Type *EltTy = VT->getElementType();
3627 for (unsigned i = 0; i != NumElts; ++i) {
3629 int SrcVal = SVI.getMaskValue(i);
3630 if ((unsigned)SrcVal >= NumElts*2) {
3631 Out << " 0/*undef*/ ";
3633 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3634 if (isa<Instruction>(Op)) {
3635 // Do an extractelement of this value from the appropriate input.
3637 printType(Out, PointerType::getUnqual(EltTy));
3638 Out << ")(&" << GetValueName(Op)
3639 << "))[" << (SrcVal & (NumElts-1)) << "]";
3640 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3643 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
3652 void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3653 // Start by copying the entire aggregate value into the result variable.
3654 writeOperand(IVI.getOperand(0));
3657 // Then do the insert to update the field.
3658 Out << GetValueName(&IVI);
3659 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3661 const Type *IndexedTy =
3662 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3663 if (IndexedTy->isArrayTy())
3664 Out << ".array[" << *i << "]";
3666 Out << ".field" << *i;
3669 writeOperand(IVI.getOperand(1));
3672 void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3674 if (isa<UndefValue>(EVI.getOperand(0))) {
3676 printType(Out, EVI.getType());
3677 Out << ") 0/*UNDEF*/";
3679 Out << GetValueName(EVI.getOperand(0));
3680 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3682 const Type *IndexedTy =
3683 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3684 if (IndexedTy->isArrayTy())
3685 Out << ".array[" << *i << "]";
3687 Out << ".field" << *i;
3693 //===----------------------------------------------------------------------===//
3694 // External Interface declaration
3695 //===----------------------------------------------------------------------===//
3697 bool CTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
3698 formatted_raw_ostream &o,
3699 CodeGenFileType FileType,
3700 CodeGenOpt::Level OptLevel,
3701 bool DisableVerify) {
3702 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
3704 PM.add(createGCLoweringPass());
3705 PM.add(createLowerInvokePass());
3706 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3707 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3708 PM.add(new CWriter(o));
3709 PM.add(createGCInfoDeleter());