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/MCSymbol.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetRegistry.h"
42 #include "llvm/Support/CallSite.h"
43 #include "llvm/Support/CFG.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/GetElementPtrTypeIterator.h"
47 #include "llvm/Support/InstVisitor.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/System/Host.h"
50 #include "llvm/Config/config.h"
54 extern "C" void LLVMInitializeCBackendTarget() {
55 // Register the target.
56 RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
60 class CBEMCAsmInfo : public MCAsmInfo {
64 PrivateGlobalPrefix = "";
67 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
68 /// any unnamed structure types that are used by the program, and merges
69 /// external functions with the same name.
71 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
74 CBackendNameAllUsedStructsAndMergeFunctions()
76 void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.addRequired<FindUsedTypes>();
80 virtual const char *getPassName() const {
81 return "C backend type canonicalizer";
84 virtual bool runOnModule(Module &M);
87 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
89 /// CWriter - This class is the main chunk of code that converts an LLVM
90 /// module to a C translation unit.
91 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
92 formatted_raw_ostream &Out;
93 IntrinsicLowering *IL;
96 const Module *TheModule;
97 const MCAsmInfo* TAsm;
99 std::map<const Type *, std::string> TypeNames;
100 std::map<const ConstantFP *, unsigned> FPConstantMap;
101 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
102 std::set<const Argument*> ByValParams;
104 unsigned OpaqueCounter;
105 DenseMap<const Value*, unsigned> AnonValueNumbers;
106 unsigned NextAnonValueNumber;
110 explicit CWriter(formatted_raw_ostream &o)
111 : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
112 TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
116 virtual const char *getPassName() const { return "C backend"; }
118 void getAnalysisUsage(AnalysisUsage &AU) const {
119 AU.addRequired<LoopInfo>();
120 AU.setPreservesAll();
123 virtual bool doInitialization(Module &M);
125 bool runOnFunction(Function &F) {
126 // Do not codegen any 'available_externally' functions at all, they have
127 // definitions outside the translation unit.
128 if (F.hasAvailableExternallyLinkage())
131 LI = &getAnalysis<LoopInfo>();
133 // Get rid of intrinsics we can't handle.
136 // Output all floating point constants that cannot be printed accurately.
137 printFloatingPointConstants(F);
143 virtual bool doFinalization(Module &M) {
148 FPConstantMap.clear();
151 intrinsicPrototypesAlreadyGenerated.clear();
155 raw_ostream &printType(raw_ostream &Out, const Type *Ty,
156 bool isSigned = false,
157 const std::string &VariableName = "",
158 bool IgnoreName = false,
159 const AttrListPtr &PAL = AttrListPtr());
160 raw_ostream &printSimpleType(raw_ostream &Out, const Type *Ty,
162 const std::string &NameSoFar = "");
164 void printStructReturnPointerFunctionType(raw_ostream &Out,
165 const AttrListPtr &PAL,
166 const PointerType *Ty);
168 /// writeOperandDeref - Print the result of dereferencing the specified
169 /// operand with '*'. This is equivalent to printing '*' then using
170 /// writeOperand, but avoids excess syntax in some cases.
171 void writeOperandDeref(Value *Operand) {
172 if (isAddressExposed(Operand)) {
173 // Already something with an address exposed.
174 writeOperandInternal(Operand);
177 writeOperand(Operand);
182 void writeOperand(Value *Operand, bool Static = false);
183 void writeInstComputationInline(Instruction &I);
184 void writeOperandInternal(Value *Operand, bool Static = false);
185 void writeOperandWithCast(Value* Operand, unsigned Opcode);
186 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
187 bool writeInstructionCast(const Instruction &I);
189 void writeMemoryAccess(Value *Operand, const Type *OperandType,
190 bool IsVolatile, unsigned Alignment);
193 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
195 void lowerIntrinsics(Function &F);
197 void printModule(Module *M);
198 void printModuleTypes(const TypeSymbolTable &ST);
199 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
200 void printFloatingPointConstants(Function &F);
201 void printFloatingPointConstants(const Constant *C);
202 void printFunctionSignature(const Function *F, bool Prototype);
204 void printFunction(Function &);
205 void printBasicBlock(BasicBlock *BB);
206 void printLoop(Loop *L);
208 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
209 void printConstant(Constant *CPV, bool Static);
210 void printConstantWithCast(Constant *CPV, unsigned Opcode);
211 bool printConstExprCast(const ConstantExpr *CE, bool Static);
212 void printConstantArray(ConstantArray *CPA, bool Static);
213 void printConstantVector(ConstantVector *CV, bool Static);
215 /// isAddressExposed - Return true if the specified value's name needs to
216 /// have its address taken in order to get a C value of the correct type.
217 /// This happens for global variables, byval parameters, and direct allocas.
218 bool isAddressExposed(const Value *V) const {
219 if (const Argument *A = dyn_cast<Argument>(V))
220 return ByValParams.count(A);
221 return isa<GlobalVariable>(V) || isDirectAlloca(V);
224 // isInlinableInst - Attempt to inline instructions into their uses to build
225 // trees as much as possible. To do this, we have to consistently decide
226 // what is acceptable to inline, so that variable declarations don't get
227 // printed and an extra copy of the expr is not emitted.
229 static bool isInlinableInst(const Instruction &I) {
230 // Always inline cmp instructions, even if they are shared by multiple
231 // expressions. GCC generates horrible code if we don't.
235 // Must be an expression, must be used exactly once. If it is dead, we
236 // emit it inline where it would go.
237 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
238 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
239 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
240 isa<InsertValueInst>(I))
241 // Don't inline a load across a store or other bad things!
244 // Must not be used in inline asm, extractelement, or shufflevector.
246 const Instruction &User = cast<Instruction>(*I.use_back());
247 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
248 isa<ShuffleVectorInst>(User))
252 // Only inline instruction it if it's use is in the same BB as the inst.
253 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
256 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
257 // variables which are accessed with the & operator. This causes GCC to
258 // generate significantly better code than to emit alloca calls directly.
260 static const AllocaInst *isDirectAlloca(const Value *V) {
261 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
262 if (!AI) return false;
263 if (AI->isArrayAllocation())
264 return 0; // FIXME: we can also inline fixed size array allocas!
265 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
270 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
271 static bool isInlineAsm(const Instruction& I) {
272 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
277 // Instruction visitation functions
278 friend class InstVisitor<CWriter>;
280 void visitReturnInst(ReturnInst &I);
281 void visitBranchInst(BranchInst &I);
282 void visitSwitchInst(SwitchInst &I);
283 void visitIndirectBrInst(IndirectBrInst &I);
284 void visitInvokeInst(InvokeInst &I) {
285 llvm_unreachable("Lowerinvoke pass didn't work!");
288 void visitUnwindInst(UnwindInst &I) {
289 llvm_unreachable("Lowerinvoke pass didn't work!");
291 void visitUnreachableInst(UnreachableInst &I);
293 void visitPHINode(PHINode &I);
294 void visitBinaryOperator(Instruction &I);
295 void visitICmpInst(ICmpInst &I);
296 void visitFCmpInst(FCmpInst &I);
298 void visitCastInst (CastInst &I);
299 void visitSelectInst(SelectInst &I);
300 void visitCallInst (CallInst &I);
301 void visitInlineAsm(CallInst &I);
302 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
304 void visitAllocaInst(AllocaInst &I);
305 void visitLoadInst (LoadInst &I);
306 void visitStoreInst (StoreInst &I);
307 void visitGetElementPtrInst(GetElementPtrInst &I);
308 void visitVAArgInst (VAArgInst &I);
310 void visitInsertElementInst(InsertElementInst &I);
311 void visitExtractElementInst(ExtractElementInst &I);
312 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
314 void visitInsertValueInst(InsertValueInst &I);
315 void visitExtractValueInst(ExtractValueInst &I);
317 void visitInstruction(Instruction &I) {
319 errs() << "C Writer does not know about " << I;
324 void outputLValue(Instruction *I) {
325 Out << " " << GetValueName(I) << " = ";
328 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
329 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
330 BasicBlock *Successor, unsigned Indent);
331 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
333 void printGEPExpression(Value *Ptr, gep_type_iterator I,
334 gep_type_iterator E, bool Static);
336 std::string GetValueName(const Value *Operand);
340 char CWriter::ID = 0;
343 static std::string CBEMangle(const std::string &S) {
346 for (unsigned i = 0, e = S.size(); i != e; ++i)
347 if (isalnum(S[i]) || S[i] == '_') {
351 Result += 'A'+(S[i]&15);
352 Result += 'A'+((S[i]>>4)&15);
359 /// This method inserts names for any unnamed structure types that are used by
360 /// the program, and removes names from structure types that are not used by the
363 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
364 // Get a set of types that are used by the program...
365 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
367 // Loop over the module symbol table, removing types from UT that are
368 // already named, and removing names for types that are not used.
370 TypeSymbolTable &TST = M.getTypeSymbolTable();
371 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
373 TypeSymbolTable::iterator I = TI++;
375 // If this isn't a struct or array type, remove it from our set of types
376 // to name. This simplifies emission later.
377 if (!I->second->isStructTy() && !I->second->isOpaqueTy() &&
378 !I->second->isArrayTy()) {
381 // If this is not used, remove it from the symbol table.
382 std::set<const Type *>::iterator UTI = UT.find(I->second);
386 UT.erase(UTI); // Only keep one name for this type.
390 // UT now contains types that are not named. Loop over it, naming
393 bool Changed = false;
394 unsigned RenameCounter = 0;
395 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
397 if ((*I)->isStructTy() || (*I)->isArrayTy()) {
398 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
404 // Loop over all external functions and globals. If we have two with
405 // identical names, merge them.
406 // FIXME: This code should disappear when we don't allow values with the same
407 // names when they have different types!
408 std::map<std::string, GlobalValue*> ExtSymbols;
409 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
411 if (GV->isDeclaration() && GV->hasName()) {
412 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
413 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
415 // Found a conflict, replace this global with the previous one.
416 GlobalValue *OldGV = X.first->second;
417 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
418 GV->eraseFromParent();
423 // Do the same for globals.
424 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
426 GlobalVariable *GV = I++;
427 if (GV->isDeclaration() && GV->hasName()) {
428 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
429 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
431 // Found a conflict, replace this global with the previous one.
432 GlobalValue *OldGV = X.first->second;
433 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
434 GV->eraseFromParent();
443 /// printStructReturnPointerFunctionType - This is like printType for a struct
444 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
445 /// print it as "Struct (*)(...)", for struct return functions.
446 void CWriter::printStructReturnPointerFunctionType(raw_ostream &Out,
447 const AttrListPtr &PAL,
448 const PointerType *TheTy) {
449 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
451 raw_string_ostream FunctionInnards(tstr);
452 FunctionInnards << " (*) (";
453 bool PrintedType = false;
455 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
456 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
458 for (++I, ++Idx; I != E; ++I, ++Idx) {
460 FunctionInnards << ", ";
461 const Type *ArgTy = *I;
462 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
463 assert(ArgTy->isPointerTy());
464 ArgTy = cast<PointerType>(ArgTy)->getElementType();
466 printType(FunctionInnards, ArgTy,
467 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
470 if (FTy->isVarArg()) {
472 FunctionInnards << ", ...";
473 } else if (!PrintedType) {
474 FunctionInnards << "void";
476 FunctionInnards << ')';
477 printType(Out, RetTy,
478 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), FunctionInnards.str());
482 CWriter::printSimpleType(raw_ostream &Out, const Type *Ty, bool isSigned,
483 const std::string &NameSoFar) {
484 assert((Ty->isPrimitiveType() || Ty->isIntegerTy() || Ty->isVectorTy()) &&
485 "Invalid type for printSimpleType");
486 switch (Ty->getTypeID()) {
487 case Type::VoidTyID: return Out << "void " << NameSoFar;
488 case Type::IntegerTyID: {
489 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
491 return Out << "bool " << NameSoFar;
492 else if (NumBits <= 8)
493 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
494 else if (NumBits <= 16)
495 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
496 else if (NumBits <= 32)
497 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
498 else if (NumBits <= 64)
499 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
501 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
502 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
505 case Type::FloatTyID: return Out << "float " << NameSoFar;
506 case Type::DoubleTyID: return Out << "double " << NameSoFar;
507 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
508 // present matches host 'long double'.
509 case Type::X86_FP80TyID:
510 case Type::PPC_FP128TyID:
511 case Type::FP128TyID: return Out << "long double " << NameSoFar;
513 case Type::VectorTyID: {
514 const VectorType *VTy = cast<VectorType>(Ty);
515 return printSimpleType(Out, VTy->getElementType(), isSigned,
516 " __attribute__((vector_size(" +
517 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
522 errs() << "Unknown primitive type: " << *Ty << "\n";
528 // Pass the Type* and the variable name and this prints out the variable
531 raw_ostream &CWriter::printType(raw_ostream &Out, const Type *Ty,
532 bool isSigned, const std::string &NameSoFar,
533 bool IgnoreName, const AttrListPtr &PAL) {
534 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || Ty->isVectorTy()) {
535 printSimpleType(Out, Ty, isSigned, NameSoFar);
539 // Check to see if the type is named.
540 if (!IgnoreName || Ty->isOpaqueTy()) {
541 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
542 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
545 switch (Ty->getTypeID()) {
546 case Type::FunctionTyID: {
547 const FunctionType *FTy = cast<FunctionType>(Ty);
549 raw_string_ostream FunctionInnards(tstr);
550 FunctionInnards << " (" << NameSoFar << ") (";
552 for (FunctionType::param_iterator I = FTy->param_begin(),
553 E = FTy->param_end(); I != E; ++I) {
554 const Type *ArgTy = *I;
555 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
556 assert(ArgTy->isPointerTy());
557 ArgTy = cast<PointerType>(ArgTy)->getElementType();
559 if (I != FTy->param_begin())
560 FunctionInnards << ", ";
561 printType(FunctionInnards, ArgTy,
562 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
565 if (FTy->isVarArg()) {
566 if (FTy->getNumParams())
567 FunctionInnards << ", ...";
568 } else if (!FTy->getNumParams()) {
569 FunctionInnards << "void";
571 FunctionInnards << ')';
572 printType(Out, FTy->getReturnType(),
573 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), FunctionInnards.str());
576 case Type::StructTyID: {
577 const StructType *STy = cast<StructType>(Ty);
578 Out << NameSoFar + " {\n";
580 for (StructType::element_iterator I = STy->element_begin(),
581 E = STy->element_end(); I != E; ++I) {
583 printType(Out, *I, false, "field" + utostr(Idx++));
588 Out << " __attribute__ ((packed))";
592 case Type::PointerTyID: {
593 const PointerType *PTy = cast<PointerType>(Ty);
594 std::string ptrName = "*" + NameSoFar;
596 if (PTy->getElementType()->isArrayTy() ||
597 PTy->getElementType()->isVectorTy())
598 ptrName = "(" + ptrName + ")";
601 // Must be a function ptr cast!
602 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
603 return printType(Out, PTy->getElementType(), false, ptrName);
606 case Type::ArrayTyID: {
607 const ArrayType *ATy = cast<ArrayType>(Ty);
608 unsigned NumElements = ATy->getNumElements();
609 if (NumElements == 0) NumElements = 1;
610 // Arrays are wrapped in structs to allow them to have normal
611 // value semantics (avoiding the array "decay").
612 Out << NameSoFar << " { ";
613 printType(Out, ATy->getElementType(), false,
614 "array[" + utostr(NumElements) + "]");
618 case Type::OpaqueTyID: {
619 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
620 assert(TypeNames.find(Ty) == TypeNames.end());
621 TypeNames[Ty] = TyName;
622 return Out << TyName << ' ' << NameSoFar;
625 llvm_unreachable("Unhandled case in getTypeProps!");
631 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
633 // As a special case, print the array as a string if it is an array of
634 // ubytes or an array of sbytes with positive values.
636 const Type *ETy = CPA->getType()->getElementType();
637 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
638 ETy == Type::getInt8Ty(CPA->getContext()));
640 // Make sure the last character is a null char, as automatically added by C
641 if (isString && (CPA->getNumOperands() == 0 ||
642 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
647 // Keep track of whether the last number was a hexadecimal escape
648 bool LastWasHex = false;
650 // Do not include the last character, which we know is null
651 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
652 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
654 // Print it out literally if it is a printable character. The only thing
655 // to be careful about is when the last letter output was a hex escape
656 // code, in which case we have to be careful not to print out hex digits
657 // explicitly (the C compiler thinks it is a continuation of the previous
658 // character, sheesh...)
660 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
662 if (C == '"' || C == '\\')
663 Out << "\\" << (char)C;
669 case '\n': Out << "\\n"; break;
670 case '\t': Out << "\\t"; break;
671 case '\r': Out << "\\r"; break;
672 case '\v': Out << "\\v"; break;
673 case '\a': Out << "\\a"; break;
674 case '\"': Out << "\\\""; break;
675 case '\'': Out << "\\\'"; break;
678 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
679 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
688 if (CPA->getNumOperands()) {
690 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
691 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
693 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
700 void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
702 if (CP->getNumOperands()) {
704 printConstant(cast<Constant>(CP->getOperand(0)), Static);
705 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
707 printConstant(cast<Constant>(CP->getOperand(i)), Static);
713 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
714 // textually as a double (rather than as a reference to a stack-allocated
715 // variable). We decide this by converting CFP to a string and back into a
716 // double, and then checking whether the conversion results in a bit-equal
717 // double to the original value of CFP. This depends on us and the target C
718 // compiler agreeing on the conversion process (which is pretty likely since we
719 // only deal in IEEE FP).
721 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
723 // Do long doubles in hex for now.
724 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
725 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
727 APFloat APF = APFloat(CFP->getValueAPF()); // copy
728 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
729 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
730 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
732 sprintf(Buffer, "%a", APF.convertToDouble());
733 if (!strncmp(Buffer, "0x", 2) ||
734 !strncmp(Buffer, "-0x", 3) ||
735 !strncmp(Buffer, "+0x", 3))
736 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
739 std::string StrVal = ftostr(APF);
741 while (StrVal[0] == ' ')
742 StrVal.erase(StrVal.begin());
744 // Check to make sure that the stringized number is not some string like "Inf"
745 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
746 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
747 ((StrVal[0] == '-' || StrVal[0] == '+') &&
748 (StrVal[1] >= '0' && StrVal[1] <= '9')))
749 // Reparse stringized version!
750 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
755 /// Print out the casting for a cast operation. This does the double casting
756 /// necessary for conversion to the destination type, if necessary.
757 /// @brief Print a cast
758 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
759 // Print the destination type cast
761 case Instruction::UIToFP:
762 case Instruction::SIToFP:
763 case Instruction::IntToPtr:
764 case Instruction::Trunc:
765 case Instruction::BitCast:
766 case Instruction::FPExt:
767 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
769 printType(Out, DstTy);
772 case Instruction::ZExt:
773 case Instruction::PtrToInt:
774 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
776 printSimpleType(Out, DstTy, false);
779 case Instruction::SExt:
780 case Instruction::FPToSI: // For these, make sure we get a signed dest
782 printSimpleType(Out, DstTy, true);
786 llvm_unreachable("Invalid cast opcode");
789 // Print the source type cast
791 case Instruction::UIToFP:
792 case Instruction::ZExt:
794 printSimpleType(Out, SrcTy, false);
797 case Instruction::SIToFP:
798 case Instruction::SExt:
800 printSimpleType(Out, SrcTy, true);
803 case Instruction::IntToPtr:
804 case Instruction::PtrToInt:
805 // Avoid "cast to pointer from integer of different size" warnings
806 Out << "(unsigned long)";
808 case Instruction::Trunc:
809 case Instruction::BitCast:
810 case Instruction::FPExt:
811 case Instruction::FPTrunc:
812 case Instruction::FPToSI:
813 case Instruction::FPToUI:
814 break; // These don't need a source cast.
816 llvm_unreachable("Invalid cast opcode");
821 // printConstant - The LLVM Constant to C Constant converter.
822 void CWriter::printConstant(Constant *CPV, bool Static) {
823 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
824 switch (CE->getOpcode()) {
825 case Instruction::Trunc:
826 case Instruction::ZExt:
827 case Instruction::SExt:
828 case Instruction::FPTrunc:
829 case Instruction::FPExt:
830 case Instruction::UIToFP:
831 case Instruction::SIToFP:
832 case Instruction::FPToUI:
833 case Instruction::FPToSI:
834 case Instruction::PtrToInt:
835 case Instruction::IntToPtr:
836 case Instruction::BitCast:
838 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
839 if (CE->getOpcode() == Instruction::SExt &&
840 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
841 // Make sure we really sext from bool here by subtracting from 0
844 printConstant(CE->getOperand(0), Static);
845 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
846 (CE->getOpcode() == Instruction::Trunc ||
847 CE->getOpcode() == Instruction::FPToUI ||
848 CE->getOpcode() == Instruction::FPToSI ||
849 CE->getOpcode() == Instruction::PtrToInt)) {
850 // Make sure we really truncate to bool here by anding with 1
856 case Instruction::GetElementPtr:
858 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
859 gep_type_end(CPV), Static);
862 case Instruction::Select:
864 printConstant(CE->getOperand(0), Static);
866 printConstant(CE->getOperand(1), Static);
868 printConstant(CE->getOperand(2), Static);
871 case Instruction::Add:
872 case Instruction::FAdd:
873 case Instruction::Sub:
874 case Instruction::FSub:
875 case Instruction::Mul:
876 case Instruction::FMul:
877 case Instruction::SDiv:
878 case Instruction::UDiv:
879 case Instruction::FDiv:
880 case Instruction::URem:
881 case Instruction::SRem:
882 case Instruction::FRem:
883 case Instruction::And:
884 case Instruction::Or:
885 case Instruction::Xor:
886 case Instruction::ICmp:
887 case Instruction::Shl:
888 case Instruction::LShr:
889 case Instruction::AShr:
892 bool NeedsClosingParens = printConstExprCast(CE, Static);
893 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
894 switch (CE->getOpcode()) {
895 case Instruction::Add:
896 case Instruction::FAdd: Out << " + "; break;
897 case Instruction::Sub:
898 case Instruction::FSub: Out << " - "; break;
899 case Instruction::Mul:
900 case Instruction::FMul: Out << " * "; break;
901 case Instruction::URem:
902 case Instruction::SRem:
903 case Instruction::FRem: Out << " % "; break;
904 case Instruction::UDiv:
905 case Instruction::SDiv:
906 case Instruction::FDiv: Out << " / "; break;
907 case Instruction::And: Out << " & "; break;
908 case Instruction::Or: Out << " | "; break;
909 case Instruction::Xor: Out << " ^ "; break;
910 case Instruction::Shl: Out << " << "; break;
911 case Instruction::LShr:
912 case Instruction::AShr: Out << " >> "; break;
913 case Instruction::ICmp:
914 switch (CE->getPredicate()) {
915 case ICmpInst::ICMP_EQ: Out << " == "; break;
916 case ICmpInst::ICMP_NE: Out << " != "; break;
917 case ICmpInst::ICMP_SLT:
918 case ICmpInst::ICMP_ULT: Out << " < "; break;
919 case ICmpInst::ICMP_SLE:
920 case ICmpInst::ICMP_ULE: Out << " <= "; break;
921 case ICmpInst::ICMP_SGT:
922 case ICmpInst::ICMP_UGT: Out << " > "; break;
923 case ICmpInst::ICMP_SGE:
924 case ICmpInst::ICMP_UGE: Out << " >= "; break;
925 default: llvm_unreachable("Illegal ICmp predicate");
928 default: llvm_unreachable("Illegal opcode here!");
930 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
931 if (NeedsClosingParens)
936 case Instruction::FCmp: {
938 bool NeedsClosingParens = printConstExprCast(CE, Static);
939 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
941 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
945 switch (CE->getPredicate()) {
946 default: llvm_unreachable("Illegal FCmp predicate");
947 case FCmpInst::FCMP_ORD: op = "ord"; break;
948 case FCmpInst::FCMP_UNO: op = "uno"; break;
949 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
950 case FCmpInst::FCMP_UNE: op = "une"; break;
951 case FCmpInst::FCMP_ULT: op = "ult"; break;
952 case FCmpInst::FCMP_ULE: op = "ule"; break;
953 case FCmpInst::FCMP_UGT: op = "ugt"; break;
954 case FCmpInst::FCMP_UGE: op = "uge"; break;
955 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
956 case FCmpInst::FCMP_ONE: op = "one"; break;
957 case FCmpInst::FCMP_OLT: op = "olt"; break;
958 case FCmpInst::FCMP_OLE: op = "ole"; break;
959 case FCmpInst::FCMP_OGT: op = "ogt"; break;
960 case FCmpInst::FCMP_OGE: op = "oge"; break;
962 Out << "llvm_fcmp_" << op << "(";
963 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
965 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
968 if (NeedsClosingParens)
975 errs() << "CWriter Error: Unhandled constant expression: "
980 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
982 printType(Out, CPV->getType()); // sign doesn't matter
984 if (!CPV->getType()->isVectorTy()) {
992 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
993 const Type* Ty = CI->getType();
994 if (Ty == Type::getInt1Ty(CPV->getContext()))
995 Out << (CI->getZExtValue() ? '1' : '0');
996 else if (Ty == Type::getInt32Ty(CPV->getContext()))
997 Out << CI->getZExtValue() << 'u';
998 else if (Ty->getPrimitiveSizeInBits() > 32)
999 Out << CI->getZExtValue() << "ull";
1002 printSimpleType(Out, Ty, false) << ')';
1003 if (CI->isMinValue(true))
1004 Out << CI->getZExtValue() << 'u';
1006 Out << CI->getSExtValue();
1012 switch (CPV->getType()->getTypeID()) {
1013 case Type::FloatTyID:
1014 case Type::DoubleTyID:
1015 case Type::X86_FP80TyID:
1016 case Type::PPC_FP128TyID:
1017 case Type::FP128TyID: {
1018 ConstantFP *FPC = cast<ConstantFP>(CPV);
1019 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1020 if (I != FPConstantMap.end()) {
1021 // Because of FP precision problems we must load from a stack allocated
1022 // value that holds the value in hex.
1023 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1025 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1028 << "*)&FPConstant" << I->second << ')';
1031 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
1032 V = FPC->getValueAPF().convertToFloat();
1033 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
1034 V = FPC->getValueAPF().convertToDouble();
1036 // Long double. Convert the number to double, discarding precision.
1037 // This is not awesome, but it at least makes the CBE output somewhat
1039 APFloat Tmp = FPC->getValueAPF();
1041 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1042 V = Tmp.convertToDouble();
1048 // FIXME the actual NaN bits should be emitted.
1049 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1051 const unsigned long QuietNaN = 0x7ff8UL;
1052 //const unsigned long SignalNaN = 0x7ff4UL;
1054 // We need to grab the first part of the FP #
1057 uint64_t ll = DoubleToBits(V);
1058 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1060 std::string Num(&Buffer[0], &Buffer[6]);
1061 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1063 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
1064 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1065 << Buffer << "\") /*nan*/ ";
1067 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1068 << Buffer << "\") /*nan*/ ";
1069 } else if (IsInf(V)) {
1071 if (V < 0) Out << '-';
1072 Out << "LLVM_INF" <<
1073 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
1077 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1078 // Print out the constant as a floating point number.
1080 sprintf(Buffer, "%a", V);
1083 Num = ftostr(FPC->getValueAPF());
1091 case Type::ArrayTyID:
1092 // Use C99 compound expression literal initializer syntax.
1095 printType(Out, CPV->getType());
1098 Out << "{ "; // Arrays are wrapped in struct types.
1099 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
1100 printConstantArray(CA, Static);
1102 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1103 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1105 if (AT->getNumElements()) {
1107 Constant *CZ = Constant::getNullValue(AT->getElementType());
1108 printConstant(CZ, Static);
1109 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1111 printConstant(CZ, Static);
1116 Out << " }"; // Arrays are wrapped in struct types.
1119 case Type::VectorTyID:
1120 // Use C99 compound expression literal initializer syntax.
1123 printType(Out, CPV->getType());
1126 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
1127 printConstantVector(CV, Static);
1129 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1130 const VectorType *VT = cast<VectorType>(CPV->getType());
1132 Constant *CZ = Constant::getNullValue(VT->getElementType());
1133 printConstant(CZ, Static);
1134 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1136 printConstant(CZ, Static);
1142 case Type::StructTyID:
1143 // Use C99 compound expression literal initializer syntax.
1146 printType(Out, CPV->getType());
1149 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1150 const StructType *ST = cast<StructType>(CPV->getType());
1152 if (ST->getNumElements()) {
1154 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
1155 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1157 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
1163 if (CPV->getNumOperands()) {
1165 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
1166 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1168 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
1175 case Type::PointerTyID:
1176 if (isa<ConstantPointerNull>(CPV)) {
1178 printType(Out, CPV->getType()); // sign doesn't matter
1179 Out << ")/*NULL*/0)";
1181 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1182 writeOperand(GV, Static);
1188 errs() << "Unknown constant type: " << *CPV << "\n";
1190 llvm_unreachable(0);
1194 // Some constant expressions need to be casted back to the original types
1195 // because their operands were casted to the expected type. This function takes
1196 // care of detecting that case and printing the cast for the ConstantExpr.
1197 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
1198 bool NeedsExplicitCast = false;
1199 const Type *Ty = CE->getOperand(0)->getType();
1200 bool TypeIsSigned = false;
1201 switch (CE->getOpcode()) {
1202 case Instruction::Add:
1203 case Instruction::Sub:
1204 case Instruction::Mul:
1205 // We need to cast integer arithmetic so that it is always performed
1206 // as unsigned, to avoid undefined behavior on overflow.
1207 case Instruction::LShr:
1208 case Instruction::URem:
1209 case Instruction::UDiv: NeedsExplicitCast = true; break;
1210 case Instruction::AShr:
1211 case Instruction::SRem:
1212 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1213 case Instruction::SExt:
1215 NeedsExplicitCast = true;
1216 TypeIsSigned = true;
1218 case Instruction::ZExt:
1219 case Instruction::Trunc:
1220 case Instruction::FPTrunc:
1221 case Instruction::FPExt:
1222 case Instruction::UIToFP:
1223 case Instruction::SIToFP:
1224 case Instruction::FPToUI:
1225 case Instruction::FPToSI:
1226 case Instruction::PtrToInt:
1227 case Instruction::IntToPtr:
1228 case Instruction::BitCast:
1230 NeedsExplicitCast = true;
1234 if (NeedsExplicitCast) {
1236 if (Ty->isIntegerTy() && Ty != Type::getInt1Ty(Ty->getContext()))
1237 printSimpleType(Out, Ty, TypeIsSigned);
1239 printType(Out, Ty); // not integer, sign doesn't matter
1242 return NeedsExplicitCast;
1245 // Print a constant assuming that it is the operand for a given Opcode. The
1246 // opcodes that care about sign need to cast their operands to the expected
1247 // type before the operation proceeds. This function does the casting.
1248 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1250 // Extract the operand's type, we'll need it.
1251 const Type* OpTy = CPV->getType();
1253 // Indicate whether to do the cast or not.
1254 bool shouldCast = false;
1255 bool typeIsSigned = false;
1257 // Based on the Opcode for which this Constant is being written, determine
1258 // the new type to which the operand should be casted by setting the value
1259 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1263 // for most instructions, it doesn't matter
1265 case Instruction::Add:
1266 case Instruction::Sub:
1267 case Instruction::Mul:
1268 // We need to cast integer arithmetic so that it is always performed
1269 // as unsigned, to avoid undefined behavior on overflow.
1270 case Instruction::LShr:
1271 case Instruction::UDiv:
1272 case Instruction::URem:
1275 case Instruction::AShr:
1276 case Instruction::SDiv:
1277 case Instruction::SRem:
1279 typeIsSigned = true;
1283 // Write out the casted constant if we should, otherwise just write the
1287 printSimpleType(Out, OpTy, typeIsSigned);
1289 printConstant(CPV, false);
1292 printConstant(CPV, false);
1295 std::string CWriter::GetValueName(const Value *Operand) {
1296 // Mangle globals with the standard mangler interface for LLC compatibility.
1297 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1298 SmallString<128> Str;
1299 Mang->getNameWithPrefix(Str, GV, false);
1300 return CBEMangle(Str.str().str());
1303 std::string Name = Operand->getName();
1305 if (Name.empty()) { // Assign unique names to local temporaries.
1306 unsigned &No = AnonValueNumbers[Operand];
1308 No = ++NextAnonValueNumber;
1309 Name = "tmp__" + utostr(No);
1312 std::string VarName;
1313 VarName.reserve(Name.capacity());
1315 for (std::string::iterator I = Name.begin(), E = Name.end();
1319 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1320 (ch >= '0' && ch <= '9') || ch == '_')) {
1322 sprintf(buffer, "_%x_", ch);
1328 return "llvm_cbe_" + VarName;
1331 /// writeInstComputationInline - Emit the computation for the specified
1332 /// instruction inline, with no destination provided.
1333 void CWriter::writeInstComputationInline(Instruction &I) {
1334 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1336 const Type *Ty = I.getType();
1337 if (Ty->isIntegerTy() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1338 Ty!=Type::getInt8Ty(I.getContext()) &&
1339 Ty!=Type::getInt16Ty(I.getContext()) &&
1340 Ty!=Type::getInt32Ty(I.getContext()) &&
1341 Ty!=Type::getInt64Ty(I.getContext()))) {
1342 llvm_report_error("The C backend does not currently support integer "
1343 "types of widths other than 1, 8, 16, 32, 64.\n"
1344 "This is being tracked as PR 4158.");
1347 // If this is a non-trivial bool computation, make sure to truncate down to
1348 // a 1 bit value. This is important because we want "add i1 x, y" to return
1349 // "0" when x and y are true, not "2" for example.
1350 bool NeedBoolTrunc = false;
1351 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1352 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1353 NeedBoolTrunc = true;
1365 void CWriter::writeOperandInternal(Value *Operand, bool Static) {
1366 if (Instruction *I = dyn_cast<Instruction>(Operand))
1367 // Should we inline this instruction to build a tree?
1368 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1370 writeInstComputationInline(*I);
1375 Constant* CPV = dyn_cast<Constant>(Operand);
1377 if (CPV && !isa<GlobalValue>(CPV))
1378 printConstant(CPV, Static);
1380 Out << GetValueName(Operand);
1383 void CWriter::writeOperand(Value *Operand, bool Static) {
1384 bool isAddressImplicit = isAddressExposed(Operand);
1385 if (isAddressImplicit)
1386 Out << "(&"; // Global variables are referenced as their addresses by llvm
1388 writeOperandInternal(Operand, Static);
1390 if (isAddressImplicit)
1394 // Some instructions need to have their result value casted back to the
1395 // original types because their operands were casted to the expected type.
1396 // This function takes care of detecting that case and printing the cast
1397 // for the Instruction.
1398 bool CWriter::writeInstructionCast(const Instruction &I) {
1399 const Type *Ty = I.getOperand(0)->getType();
1400 switch (I.getOpcode()) {
1401 case Instruction::Add:
1402 case Instruction::Sub:
1403 case Instruction::Mul:
1404 // We need to cast integer arithmetic so that it is always performed
1405 // as unsigned, to avoid undefined behavior on overflow.
1406 case Instruction::LShr:
1407 case Instruction::URem:
1408 case Instruction::UDiv:
1410 printSimpleType(Out, Ty, false);
1413 case Instruction::AShr:
1414 case Instruction::SRem:
1415 case Instruction::SDiv:
1417 printSimpleType(Out, Ty, true);
1425 // Write the operand with a cast to another type based on the Opcode being used.
1426 // This will be used in cases where an instruction has specific type
1427 // requirements (usually signedness) for its operands.
1428 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1430 // Extract the operand's type, we'll need it.
1431 const Type* OpTy = Operand->getType();
1433 // Indicate whether to do the cast or not.
1434 bool shouldCast = false;
1436 // Indicate whether the cast should be to a signed type or not.
1437 bool castIsSigned = false;
1439 // Based on the Opcode for which this Operand is being written, determine
1440 // the new type to which the operand should be casted by setting the value
1441 // of OpTy. If we change OpTy, also set shouldCast to true.
1444 // for most instructions, it doesn't matter
1446 case Instruction::Add:
1447 case Instruction::Sub:
1448 case Instruction::Mul:
1449 // We need to cast integer arithmetic so that it is always performed
1450 // as unsigned, to avoid undefined behavior on overflow.
1451 case Instruction::LShr:
1452 case Instruction::UDiv:
1453 case Instruction::URem: // Cast to unsigned first
1455 castIsSigned = false;
1457 case Instruction::GetElementPtr:
1458 case Instruction::AShr:
1459 case Instruction::SDiv:
1460 case Instruction::SRem: // Cast to signed first
1462 castIsSigned = true;
1466 // Write out the casted operand if we should, otherwise just write the
1470 printSimpleType(Out, OpTy, castIsSigned);
1472 writeOperand(Operand);
1475 writeOperand(Operand);
1478 // Write the operand with a cast to another type based on the icmp predicate
1480 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1481 // This has to do a cast to ensure the operand has the right signedness.
1482 // Also, if the operand is a pointer, we make sure to cast to an integer when
1483 // doing the comparison both for signedness and so that the C compiler doesn't
1484 // optimize things like "p < NULL" to false (p may contain an integer value
1486 bool shouldCast = Cmp.isRelational();
1488 // Write out the casted operand if we should, otherwise just write the
1491 writeOperand(Operand);
1495 // Should this be a signed comparison? If so, convert to signed.
1496 bool castIsSigned = Cmp.isSigned();
1498 // If the operand was a pointer, convert to a large integer type.
1499 const Type* OpTy = Operand->getType();
1500 if (OpTy->isPointerTy())
1501 OpTy = TD->getIntPtrType(Operand->getContext());
1504 printSimpleType(Out, OpTy, castIsSigned);
1506 writeOperand(Operand);
1510 // generateCompilerSpecificCode - This is where we add conditional compilation
1511 // directives to cater to specific compilers as need be.
1513 static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
1514 const TargetData *TD) {
1515 // Alloca is hard to get, and we don't want to include stdlib.h here.
1516 Out << "/* get a declaration for alloca */\n"
1517 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1518 << "#define alloca(x) __builtin_alloca((x))\n"
1519 << "#define _alloca(x) __builtin_alloca((x))\n"
1520 << "#elif defined(__APPLE__)\n"
1521 << "extern void *__builtin_alloca(unsigned long);\n"
1522 << "#define alloca(x) __builtin_alloca(x)\n"
1523 << "#define longjmp _longjmp\n"
1524 << "#define setjmp _setjmp\n"
1525 << "#elif defined(__sun__)\n"
1526 << "#if defined(__sparcv9)\n"
1527 << "extern void *__builtin_alloca(unsigned long);\n"
1529 << "extern void *__builtin_alloca(unsigned int);\n"
1531 << "#define alloca(x) __builtin_alloca(x)\n"
1532 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
1533 << "#define alloca(x) __builtin_alloca(x)\n"
1534 << "#elif defined(_MSC_VER)\n"
1535 << "#define inline _inline\n"
1536 << "#define alloca(x) _alloca(x)\n"
1538 << "#include <alloca.h>\n"
1541 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1542 // If we aren't being compiled with GCC, just drop these attributes.
1543 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1544 << "#define __attribute__(X)\n"
1547 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1548 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1549 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1550 << "#elif defined(__GNUC__)\n"
1551 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1553 << "#define __EXTERNAL_WEAK__\n"
1556 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1557 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1558 << "#define __ATTRIBUTE_WEAK__\n"
1559 << "#elif defined(__GNUC__)\n"
1560 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1562 << "#define __ATTRIBUTE_WEAK__\n"
1565 // Add hidden visibility support. FIXME: APPLE_CC?
1566 Out << "#if defined(__GNUC__)\n"
1567 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1570 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1571 // From the GCC documentation:
1573 // double __builtin_nan (const char *str)
1575 // This is an implementation of the ISO C99 function nan.
1577 // Since ISO C99 defines this function in terms of strtod, which we do
1578 // not implement, a description of the parsing is in order. The string is
1579 // parsed as by strtol; that is, the base is recognized by leading 0 or
1580 // 0x prefixes. The number parsed is placed in the significand such that
1581 // the least significant bit of the number is at the least significant
1582 // bit of the significand. The number is truncated to fit the significand
1583 // field provided. The significand is forced to be a quiet NaN.
1585 // This function, if given a string literal, is evaluated early enough
1586 // that it is considered a compile-time constant.
1588 // float __builtin_nanf (const char *str)
1590 // Similar to __builtin_nan, except the return type is float.
1592 // double __builtin_inf (void)
1594 // Similar to __builtin_huge_val, except a warning is generated if the
1595 // target floating-point format does not support infinities. This
1596 // function is suitable for implementing the ISO C99 macro INFINITY.
1598 // float __builtin_inff (void)
1600 // Similar to __builtin_inf, except the return type is float.
1601 Out << "#ifdef __GNUC__\n"
1602 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1603 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1604 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1605 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1606 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1607 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1608 << "#define LLVM_PREFETCH(addr,rw,locality) "
1609 "__builtin_prefetch(addr,rw,locality)\n"
1610 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1611 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1612 << "#define LLVM_ASM __asm__\n"
1614 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1615 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1616 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1617 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1618 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1619 << "#define LLVM_INFF 0.0F /* Float */\n"
1620 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1621 << "#define __ATTRIBUTE_CTOR__\n"
1622 << "#define __ATTRIBUTE_DTOR__\n"
1623 << "#define LLVM_ASM(X)\n"
1626 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1627 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1628 << "#define __builtin_stack_restore(X) /* noop */\n"
1631 // Output typedefs for 128-bit integers. If these are needed with a
1632 // 32-bit target or with a C compiler that doesn't support mode(TI),
1633 // more drastic measures will be needed.
1634 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1635 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1636 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1639 // Output target-specific code that should be inserted into main.
1640 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1643 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1644 /// the StaticTors set.
1645 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1646 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1647 if (!InitList) return;
1649 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1650 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1651 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1653 if (CS->getOperand(1)->isNullValue())
1654 return; // Found a null terminator, exit printing.
1655 Constant *FP = CS->getOperand(1);
1656 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1658 FP = CE->getOperand(0);
1659 if (Function *F = dyn_cast<Function>(FP))
1660 StaticTors.insert(F);
1664 enum SpecialGlobalClass {
1666 GlobalCtors, GlobalDtors,
1670 /// getGlobalVariableClass - If this is a global that is specially recognized
1671 /// by LLVM, return a code that indicates how we should handle it.
1672 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1673 // If this is a global ctors/dtors list, handle it now.
1674 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1675 if (GV->getName() == "llvm.global_ctors")
1677 else if (GV->getName() == "llvm.global_dtors")
1681 // Otherwise, if it is other metadata, don't print it. This catches things
1682 // like debug information.
1683 if (GV->getSection() == "llvm.metadata")
1689 // PrintEscapedString - Print each character of the specified string, escaping
1690 // it if it is not printable or if it is an escape char.
1691 static void PrintEscapedString(const char *Str, unsigned Length,
1693 for (unsigned i = 0; i != Length; ++i) {
1694 unsigned char C = Str[i];
1695 if (isprint(C) && C != '\\' && C != '"')
1704 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1708 // PrintEscapedString - Print each character of the specified string, escaping
1709 // it if it is not printable or if it is an escape char.
1710 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1711 PrintEscapedString(Str.c_str(), Str.size(), Out);
1714 bool CWriter::doInitialization(Module &M) {
1715 FunctionPass::doInitialization(M);
1720 TD = new TargetData(&M);
1721 IL = new IntrinsicLowering(*TD);
1722 IL->AddPrototypes(M);
1725 std::string Triple = TheModule->getTargetTriple();
1727 Triple = llvm::sys::getHostTriple();
1730 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1731 TAsm = Match->createAsmInfo(Triple);
1733 TAsm = new CBEMCAsmInfo();
1734 Mang = new Mangler(*TAsm);
1736 // Keep track of which functions are static ctors/dtors so they can have
1737 // an attribute added to their prototypes.
1738 std::set<Function*> StaticCtors, StaticDtors;
1739 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1741 switch (getGlobalVariableClass(I)) {
1744 FindStaticTors(I, StaticCtors);
1747 FindStaticTors(I, StaticDtors);
1752 // get declaration for alloca
1753 Out << "/* Provide Declarations */\n";
1754 Out << "#include <stdarg.h>\n"; // Varargs support
1755 Out << "#include <setjmp.h>\n"; // Unwind support
1756 generateCompilerSpecificCode(Out, TD);
1758 // Provide a definition for `bool' if not compiling with a C++ compiler.
1760 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1762 << "\n\n/* Support for floating point constants */\n"
1763 << "typedef unsigned long long ConstantDoubleTy;\n"
1764 << "typedef unsigned int ConstantFloatTy;\n"
1765 << "typedef struct { unsigned long long f1; unsigned short f2; "
1766 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1767 // This is used for both kinds of 128-bit long double; meaning differs.
1768 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1769 " ConstantFP128Ty;\n"
1770 << "\n\n/* Global Declarations */\n";
1772 // First output all the declarations for the program, because C requires
1773 // Functions & globals to be declared before they are used.
1775 if (!M.getModuleInlineAsm().empty()) {
1776 Out << "/* Module asm statements */\n"
1779 // Split the string into lines, to make it easier to read the .ll file.
1780 std::string Asm = M.getModuleInlineAsm();
1782 size_t NewLine = Asm.find_first_of('\n', CurPos);
1783 while (NewLine != std::string::npos) {
1784 // We found a newline, print the portion of the asm string from the
1785 // last newline up to this newline.
1787 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1791 NewLine = Asm.find_first_of('\n', CurPos);
1794 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1796 << "/* End Module asm statements */\n";
1799 // Loop over the symbol table, emitting all named constants...
1800 printModuleTypes(M.getTypeSymbolTable());
1802 // Global variable declarations...
1803 if (!M.global_empty()) {
1804 Out << "\n/* External Global Variable Declarations */\n";
1805 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1808 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1809 I->hasCommonLinkage())
1811 else if (I->hasDLLImportLinkage())
1812 Out << "__declspec(dllimport) ";
1814 continue; // Internal Global
1816 // Thread Local Storage
1817 if (I->isThreadLocal())
1820 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1822 if (I->hasExternalWeakLinkage())
1823 Out << " __EXTERNAL_WEAK__";
1828 // Function declarations
1829 Out << "\n/* Function Declarations */\n";
1830 Out << "double fmod(double, double);\n"; // Support for FP rem
1831 Out << "float fmodf(float, float);\n";
1832 Out << "long double fmodl(long double, long double);\n";
1834 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1835 // Don't print declarations for intrinsic functions.
1836 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
1837 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1838 if (I->hasExternalWeakLinkage())
1840 printFunctionSignature(I, true);
1841 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1842 Out << " __ATTRIBUTE_WEAK__";
1843 if (I->hasExternalWeakLinkage())
1844 Out << " __EXTERNAL_WEAK__";
1845 if (StaticCtors.count(I))
1846 Out << " __ATTRIBUTE_CTOR__";
1847 if (StaticDtors.count(I))
1848 Out << " __ATTRIBUTE_DTOR__";
1849 if (I->hasHiddenVisibility())
1850 Out << " __HIDDEN__";
1852 if (I->hasName() && I->getName()[0] == 1)
1853 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
1859 // Output the global variable declarations
1860 if (!M.global_empty()) {
1861 Out << "\n\n/* Global Variable Declarations */\n";
1862 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1864 if (!I->isDeclaration()) {
1865 // Ignore special globals, such as debug info.
1866 if (getGlobalVariableClass(I))
1869 if (I->hasLocalLinkage())
1874 // Thread Local Storage
1875 if (I->isThreadLocal())
1878 printType(Out, I->getType()->getElementType(), false,
1881 if (I->hasLinkOnceLinkage())
1882 Out << " __attribute__((common))";
1883 else if (I->hasCommonLinkage()) // FIXME is this right?
1884 Out << " __ATTRIBUTE_WEAK__";
1885 else if (I->hasWeakLinkage())
1886 Out << " __ATTRIBUTE_WEAK__";
1887 else if (I->hasExternalWeakLinkage())
1888 Out << " __EXTERNAL_WEAK__";
1889 if (I->hasHiddenVisibility())
1890 Out << " __HIDDEN__";
1895 // Output the global variable definitions and contents...
1896 if (!M.global_empty()) {
1897 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1898 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1900 if (!I->isDeclaration()) {
1901 // Ignore special globals, such as debug info.
1902 if (getGlobalVariableClass(I))
1905 if (I->hasLocalLinkage())
1907 else if (I->hasDLLImportLinkage())
1908 Out << "__declspec(dllimport) ";
1909 else if (I->hasDLLExportLinkage())
1910 Out << "__declspec(dllexport) ";
1912 // Thread Local Storage
1913 if (I->isThreadLocal())
1916 printType(Out, I->getType()->getElementType(), false,
1918 if (I->hasLinkOnceLinkage())
1919 Out << " __attribute__((common))";
1920 else if (I->hasWeakLinkage())
1921 Out << " __ATTRIBUTE_WEAK__";
1922 else if (I->hasCommonLinkage())
1923 Out << " __ATTRIBUTE_WEAK__";
1925 if (I->hasHiddenVisibility())
1926 Out << " __HIDDEN__";
1928 // If the initializer is not null, emit the initializer. If it is null,
1929 // we try to avoid emitting large amounts of zeros. The problem with
1930 // this, however, occurs when the variable has weak linkage. In this
1931 // case, the assembler will complain about the variable being both weak
1932 // and common, so we disable this optimization.
1933 // FIXME common linkage should avoid this problem.
1934 if (!I->getInitializer()->isNullValue()) {
1936 writeOperand(I->getInitializer(), true);
1937 } else if (I->hasWeakLinkage()) {
1938 // We have to specify an initializer, but it doesn't have to be
1939 // complete. If the value is an aggregate, print out { 0 }, and let
1940 // the compiler figure out the rest of the zeros.
1942 if (I->getInitializer()->getType()->isStructTy() ||
1943 I->getInitializer()->getType()->isVectorTy()) {
1945 } else if (I->getInitializer()->getType()->isArrayTy()) {
1946 // As with structs and vectors, but with an extra set of braces
1947 // because arrays are wrapped in structs.
1950 // Just print it out normally.
1951 writeOperand(I->getInitializer(), true);
1959 Out << "\n\n/* Function Bodies */\n";
1961 // Emit some helper functions for dealing with FCMP instruction's
1963 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1964 Out << "return X == X && Y == Y; }\n";
1965 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1966 Out << "return X != X || Y != Y; }\n";
1967 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
1968 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
1969 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
1970 Out << "return X != Y; }\n";
1971 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
1972 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
1973 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
1974 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
1975 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
1976 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
1977 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
1978 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
1979 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
1980 Out << "return X == Y ; }\n";
1981 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
1982 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
1983 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
1984 Out << "return X < Y ; }\n";
1985 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
1986 Out << "return X > Y ; }\n";
1987 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
1988 Out << "return X <= Y ; }\n";
1989 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
1990 Out << "return X >= Y ; }\n";
1995 /// Output all floating point constants that cannot be printed accurately...
1996 void CWriter::printFloatingPointConstants(Function &F) {
1997 // Scan the module for floating point constants. If any FP constant is used
1998 // in the function, we want to redirect it here so that we do not depend on
1999 // the precision of the printed form, unless the printed form preserves
2002 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2004 printFloatingPointConstants(*I);
2009 void CWriter::printFloatingPointConstants(const Constant *C) {
2010 // If this is a constant expression, recursively check for constant fp values.
2011 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2012 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2013 printFloatingPointConstants(CE->getOperand(i));
2017 // Otherwise, check for a FP constant that we need to print.
2018 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2020 // Do not put in FPConstantMap if safe.
2021 isFPCSafeToPrint(FPC) ||
2022 // Already printed this constant?
2023 FPConstantMap.count(FPC))
2026 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2028 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
2029 double Val = FPC->getValueAPF().convertToDouble();
2030 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2031 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2032 << " = 0x" << utohexstr(i)
2033 << "ULL; /* " << Val << " */\n";
2034 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
2035 float Val = FPC->getValueAPF().convertToFloat();
2036 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2038 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2039 << " = 0x" << utohexstr(i)
2040 << "U; /* " << Val << " */\n";
2041 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
2042 // api needed to prevent premature destruction
2043 APInt api = FPC->getValueAPF().bitcastToAPInt();
2044 const uint64_t *p = api.getRawData();
2045 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
2046 << " = { 0x" << utohexstr(p[0])
2047 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
2048 << "}; /* Long double constant */\n";
2049 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2050 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
2051 APInt api = FPC->getValueAPF().bitcastToAPInt();
2052 const uint64_t *p = api.getRawData();
2053 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2055 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2056 << "}; /* Long double constant */\n";
2059 llvm_unreachable("Unknown float type!");
2065 /// printSymbolTable - Run through symbol table looking for type names. If a
2066 /// type name is found, emit its declaration...
2068 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2069 Out << "/* Helper union for bitcasts */\n";
2070 Out << "typedef union {\n";
2071 Out << " unsigned int Int32;\n";
2072 Out << " unsigned long long Int64;\n";
2073 Out << " float Float;\n";
2074 Out << " double Double;\n";
2075 Out << "} llvmBitCastUnion;\n";
2077 // We are only interested in the type plane of the symbol table.
2078 TypeSymbolTable::const_iterator I = TST.begin();
2079 TypeSymbolTable::const_iterator End = TST.end();
2081 // If there are no type names, exit early.
2082 if (I == End) return;
2084 // Print out forward declarations for structure types before anything else!
2085 Out << "/* Structure forward decls */\n";
2086 for (; I != End; ++I) {
2087 std::string Name = "struct " + CBEMangle("l_"+I->first);
2088 Out << Name << ";\n";
2089 TypeNames.insert(std::make_pair(I->second, Name));
2094 // Now we can print out typedefs. Above, we guaranteed that this can only be
2095 // for struct or opaque types.
2096 Out << "/* Typedefs */\n";
2097 for (I = TST.begin(); I != End; ++I) {
2098 std::string Name = CBEMangle("l_"+I->first);
2100 printType(Out, I->second, false, Name);
2106 // Keep track of which structures have been printed so far...
2107 std::set<const Type *> StructPrinted;
2109 // Loop over all structures then push them into the stack so they are
2110 // printed in the correct order.
2112 Out << "/* Structure contents */\n";
2113 for (I = TST.begin(); I != End; ++I)
2114 if (I->second->isStructTy() || I->second->isArrayTy())
2115 // Only print out used types!
2116 printContainedStructs(I->second, StructPrinted);
2119 // Push the struct onto the stack and recursively push all structs
2120 // this one depends on.
2122 // TODO: Make this work properly with vector types
2124 void CWriter::printContainedStructs(const Type *Ty,
2125 std::set<const Type*> &StructPrinted) {
2126 // Don't walk through pointers.
2127 if (Ty->isPointerTy() || Ty->isPrimitiveType() || Ty->isIntegerTy())
2130 // Print all contained types first.
2131 for (Type::subtype_iterator I = Ty->subtype_begin(),
2132 E = Ty->subtype_end(); I != E; ++I)
2133 printContainedStructs(*I, StructPrinted);
2135 if (Ty->isStructTy() || Ty->isArrayTy()) {
2136 // Check to see if we have already printed this struct.
2137 if (StructPrinted.insert(Ty).second) {
2138 // Print structure type out.
2139 std::string Name = TypeNames[Ty];
2140 printType(Out, Ty, false, Name, true);
2146 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2147 /// isStructReturn - Should this function actually return a struct by-value?
2148 bool isStructReturn = F->hasStructRetAttr();
2150 if (F->hasLocalLinkage()) Out << "static ";
2151 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2152 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2153 switch (F->getCallingConv()) {
2154 case CallingConv::X86_StdCall:
2155 Out << "__attribute__((stdcall)) ";
2157 case CallingConv::X86_FastCall:
2158 Out << "__attribute__((fastcall)) ";
2164 // Loop over the arguments, printing them...
2165 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
2166 const AttrListPtr &PAL = F->getAttributes();
2169 raw_string_ostream FunctionInnards(tstr);
2171 // Print out the name...
2172 FunctionInnards << GetValueName(F) << '(';
2174 bool PrintedArg = false;
2175 if (!F->isDeclaration()) {
2176 if (!F->arg_empty()) {
2177 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2180 // If this is a struct-return function, don't print the hidden
2181 // struct-return argument.
2182 if (isStructReturn) {
2183 assert(I != E && "Invalid struct return function!");
2188 std::string ArgName;
2189 for (; I != E; ++I) {
2190 if (PrintedArg) FunctionInnards << ", ";
2191 if (I->hasName() || !Prototype)
2192 ArgName = GetValueName(I);
2195 const Type *ArgTy = I->getType();
2196 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2197 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2198 ByValParams.insert(I);
2200 printType(FunctionInnards, ArgTy,
2201 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
2208 // Loop over the arguments, printing them.
2209 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
2212 // If this is a struct-return function, don't print the hidden
2213 // struct-return argument.
2214 if (isStructReturn) {
2215 assert(I != E && "Invalid struct return function!");
2220 for (; I != E; ++I) {
2221 if (PrintedArg) FunctionInnards << ", ";
2222 const Type *ArgTy = *I;
2223 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2224 assert(ArgTy->isPointerTy());
2225 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2227 printType(FunctionInnards, ArgTy,
2228 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
2234 // Finish printing arguments... if this is a vararg function, print the ...,
2235 // unless there are no known types, in which case, we just emit ().
2237 if (FT->isVarArg() && PrintedArg) {
2238 if (PrintedArg) FunctionInnards << ", ";
2239 FunctionInnards << "..."; // Output varargs portion of signature!
2240 } else if (!FT->isVarArg() && !PrintedArg) {
2241 FunctionInnards << "void"; // ret() -> ret(void) in C.
2243 FunctionInnards << ')';
2245 // Get the return tpe for the function.
2247 if (!isStructReturn)
2248 RetTy = F->getReturnType();
2250 // If this is a struct-return function, print the struct-return type.
2251 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2254 // Print out the return type and the signature built above.
2255 printType(Out, RetTy,
2256 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
2257 FunctionInnards.str());
2260 static inline bool isFPIntBitCast(const Instruction &I) {
2261 if (!isa<BitCastInst>(I))
2263 const Type *SrcTy = I.getOperand(0)->getType();
2264 const Type *DstTy = I.getType();
2265 return (SrcTy->isFloatingPointTy() && DstTy->isIntegerTy()) ||
2266 (DstTy->isFloatingPointTy() && SrcTy->isIntegerTy());
2269 void CWriter::printFunction(Function &F) {
2270 /// isStructReturn - Should this function actually return a struct by-value?
2271 bool isStructReturn = F.hasStructRetAttr();
2273 printFunctionSignature(&F, false);
2276 // If this is a struct return function, handle the result with magic.
2277 if (isStructReturn) {
2278 const Type *StructTy =
2279 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2281 printType(Out, StructTy, false, "StructReturn");
2282 Out << "; /* Struct return temporary */\n";
2285 printType(Out, F.arg_begin()->getType(), false,
2286 GetValueName(F.arg_begin()));
2287 Out << " = &StructReturn;\n";
2290 bool PrintedVar = false;
2292 // print local variable information for the function
2293 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2294 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2296 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2297 Out << "; /* Address-exposed local */\n";
2299 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2300 !isInlinableInst(*I)) {
2302 printType(Out, I->getType(), false, GetValueName(&*I));
2305 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2307 printType(Out, I->getType(), false,
2308 GetValueName(&*I)+"__PHI_TEMPORARY");
2313 // We need a temporary for the BitCast to use so it can pluck a value out
2314 // of a union to do the BitCast. This is separate from the need for a
2315 // variable to hold the result of the BitCast.
2316 if (isFPIntBitCast(*I)) {
2317 Out << " llvmBitCastUnion " << GetValueName(&*I)
2318 << "__BITCAST_TEMPORARY;\n";
2326 if (F.hasExternalLinkage() && F.getName() == "main")
2327 Out << " CODE_FOR_MAIN();\n";
2329 // print the basic blocks
2330 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2331 if (Loop *L = LI->getLoopFor(BB)) {
2332 if (L->getHeader() == BB && L->getParentLoop() == 0)
2335 printBasicBlock(BB);
2342 void CWriter::printLoop(Loop *L) {
2343 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2344 << "' to make GCC happy */\n";
2345 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2346 BasicBlock *BB = L->getBlocks()[i];
2347 Loop *BBLoop = LI->getLoopFor(BB);
2349 printBasicBlock(BB);
2350 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2353 Out << " } while (1); /* end of syntactic loop '"
2354 << L->getHeader()->getName() << "' */\n";
2357 void CWriter::printBasicBlock(BasicBlock *BB) {
2359 // Don't print the label for the basic block if there are no uses, or if
2360 // the only terminator use is the predecessor basic block's terminator.
2361 // We have to scan the use list because PHI nodes use basic blocks too but
2362 // do not require a label to be generated.
2364 bool NeedsLabel = false;
2365 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2366 if (isGotoCodeNecessary(*PI, BB)) {
2371 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2373 // Output all of the instructions in the basic block...
2374 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2376 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2377 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2382 writeInstComputationInline(*II);
2387 // Don't emit prefix or suffix for the terminator.
2388 visit(*BB->getTerminator());
2392 // Specific Instruction type classes... note that all of the casts are
2393 // necessary because we use the instruction classes as opaque types...
2395 void CWriter::visitReturnInst(ReturnInst &I) {
2396 // If this is a struct return function, return the temporary struct.
2397 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
2399 if (isStructReturn) {
2400 Out << " return StructReturn;\n";
2404 // Don't output a void return if this is the last basic block in the function
2405 if (I.getNumOperands() == 0 &&
2406 &*--I.getParent()->getParent()->end() == I.getParent() &&
2407 !I.getParent()->size() == 1) {
2411 if (I.getNumOperands() > 1) {
2414 printType(Out, I.getParent()->getParent()->getReturnType());
2415 Out << " llvm_cbe_mrv_temp = {\n";
2416 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2418 writeOperand(I.getOperand(i));
2424 Out << " return llvm_cbe_mrv_temp;\n";
2430 if (I.getNumOperands()) {
2432 writeOperand(I.getOperand(0));
2437 void CWriter::visitSwitchInst(SwitchInst &SI) {
2440 writeOperand(SI.getOperand(0));
2441 Out << ") {\n default:\n";
2442 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2443 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2445 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2447 writeOperand(SI.getOperand(i));
2449 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2450 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2451 printBranchToBlock(SI.getParent(), Succ, 2);
2452 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
2458 void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
2459 Out << " goto *(void*)(";
2460 writeOperand(IBI.getOperand(0));
2464 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2465 Out << " /*UNREACHABLE*/;\n";
2468 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2469 /// FIXME: This should be reenabled, but loop reordering safe!!
2472 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
2473 return true; // Not the direct successor, we need a goto.
2475 //isa<SwitchInst>(From->getTerminator())
2477 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2482 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2483 BasicBlock *Successor,
2485 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2486 PHINode *PN = cast<PHINode>(I);
2487 // Now we have to do the printing.
2488 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2489 if (!isa<UndefValue>(IV)) {
2490 Out << std::string(Indent, ' ');
2491 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2493 Out << "; /* for PHI node */\n";
2498 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2500 if (isGotoCodeNecessary(CurBB, Succ)) {
2501 Out << std::string(Indent, ' ') << " goto ";
2507 // Branch instruction printing - Avoid printing out a branch to a basic block
2508 // that immediately succeeds the current one.
2510 void CWriter::visitBranchInst(BranchInst &I) {
2512 if (I.isConditional()) {
2513 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2515 writeOperand(I.getCondition());
2518 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2519 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2521 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2522 Out << " } else {\n";
2523 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2524 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2527 // First goto not necessary, assume second one is...
2529 writeOperand(I.getCondition());
2532 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2533 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2538 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2539 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2544 // PHI nodes get copied into temporary values at the end of predecessor basic
2545 // blocks. We now need to copy these temporary values into the REAL value for
2547 void CWriter::visitPHINode(PHINode &I) {
2549 Out << "__PHI_TEMPORARY";
2553 void CWriter::visitBinaryOperator(Instruction &I) {
2554 // binary instructions, shift instructions, setCond instructions.
2555 assert(!I.getType()->isPointerTy());
2557 // We must cast the results of binary operations which might be promoted.
2558 bool needsCast = false;
2559 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2560 (I.getType() == Type::getInt16Ty(I.getContext()))
2561 || (I.getType() == Type::getFloatTy(I.getContext()))) {
2564 printType(Out, I.getType(), false);
2568 // If this is a negation operation, print it out as such. For FP, we don't
2569 // want to print "-0.0 - X".
2570 if (BinaryOperator::isNeg(&I)) {
2572 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2574 } else if (BinaryOperator::isFNeg(&I)) {
2576 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2578 } else if (I.getOpcode() == Instruction::FRem) {
2579 // Output a call to fmod/fmodf instead of emitting a%b
2580 if (I.getType() == Type::getFloatTy(I.getContext()))
2582 else if (I.getType() == Type::getDoubleTy(I.getContext()))
2584 else // all 3 flavors of long double
2586 writeOperand(I.getOperand(0));
2588 writeOperand(I.getOperand(1));
2592 // Write out the cast of the instruction's value back to the proper type
2594 bool NeedsClosingParens = writeInstructionCast(I);
2596 // Certain instructions require the operand to be forced to a specific type
2597 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2598 // below for operand 1
2599 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2601 switch (I.getOpcode()) {
2602 case Instruction::Add:
2603 case Instruction::FAdd: Out << " + "; break;
2604 case Instruction::Sub:
2605 case Instruction::FSub: Out << " - "; break;
2606 case Instruction::Mul:
2607 case Instruction::FMul: Out << " * "; break;
2608 case Instruction::URem:
2609 case Instruction::SRem:
2610 case Instruction::FRem: Out << " % "; break;
2611 case Instruction::UDiv:
2612 case Instruction::SDiv:
2613 case Instruction::FDiv: Out << " / "; break;
2614 case Instruction::And: Out << " & "; break;
2615 case Instruction::Or: Out << " | "; break;
2616 case Instruction::Xor: Out << " ^ "; break;
2617 case Instruction::Shl : Out << " << "; break;
2618 case Instruction::LShr:
2619 case Instruction::AShr: Out << " >> "; break;
2622 errs() << "Invalid operator type!" << I;
2624 llvm_unreachable(0);
2627 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2628 if (NeedsClosingParens)
2637 void CWriter::visitICmpInst(ICmpInst &I) {
2638 // We must cast the results of icmp which might be promoted.
2639 bool needsCast = false;
2641 // Write out the cast of the instruction's value back to the proper type
2643 bool NeedsClosingParens = writeInstructionCast(I);
2645 // Certain icmp predicate require the operand to be forced to a specific type
2646 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2647 // below for operand 1
2648 writeOperandWithCast(I.getOperand(0), I);
2650 switch (I.getPredicate()) {
2651 case ICmpInst::ICMP_EQ: Out << " == "; break;
2652 case ICmpInst::ICMP_NE: Out << " != "; break;
2653 case ICmpInst::ICMP_ULE:
2654 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2655 case ICmpInst::ICMP_UGE:
2656 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2657 case ICmpInst::ICMP_ULT:
2658 case ICmpInst::ICMP_SLT: Out << " < "; break;
2659 case ICmpInst::ICMP_UGT:
2660 case ICmpInst::ICMP_SGT: Out << " > "; break;
2663 errs() << "Invalid icmp predicate!" << I;
2665 llvm_unreachable(0);
2668 writeOperandWithCast(I.getOperand(1), I);
2669 if (NeedsClosingParens)
2677 void CWriter::visitFCmpInst(FCmpInst &I) {
2678 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2682 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2688 switch (I.getPredicate()) {
2689 default: llvm_unreachable("Illegal FCmp predicate");
2690 case FCmpInst::FCMP_ORD: op = "ord"; break;
2691 case FCmpInst::FCMP_UNO: op = "uno"; break;
2692 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2693 case FCmpInst::FCMP_UNE: op = "une"; break;
2694 case FCmpInst::FCMP_ULT: op = "ult"; break;
2695 case FCmpInst::FCMP_ULE: op = "ule"; break;
2696 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2697 case FCmpInst::FCMP_UGE: op = "uge"; break;
2698 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2699 case FCmpInst::FCMP_ONE: op = "one"; break;
2700 case FCmpInst::FCMP_OLT: op = "olt"; break;
2701 case FCmpInst::FCMP_OLE: op = "ole"; break;
2702 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2703 case FCmpInst::FCMP_OGE: op = "oge"; break;
2706 Out << "llvm_fcmp_" << op << "(";
2707 // Write the first operand
2708 writeOperand(I.getOperand(0));
2710 // Write the second operand
2711 writeOperand(I.getOperand(1));
2715 static const char * getFloatBitCastField(const Type *Ty) {
2716 switch (Ty->getTypeID()) {
2717 default: llvm_unreachable("Invalid Type");
2718 case Type::FloatTyID: return "Float";
2719 case Type::DoubleTyID: return "Double";
2720 case Type::IntegerTyID: {
2721 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2730 void CWriter::visitCastInst(CastInst &I) {
2731 const Type *DstTy = I.getType();
2732 const Type *SrcTy = I.getOperand(0)->getType();
2733 if (isFPIntBitCast(I)) {
2735 // These int<->float and long<->double casts need to be handled specially
2736 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2737 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2738 writeOperand(I.getOperand(0));
2739 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2740 << getFloatBitCastField(I.getType());
2746 printCast(I.getOpcode(), SrcTy, DstTy);
2748 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2749 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2750 I.getOpcode() == Instruction::SExt)
2753 writeOperand(I.getOperand(0));
2755 if (DstTy == Type::getInt1Ty(I.getContext()) &&
2756 (I.getOpcode() == Instruction::Trunc ||
2757 I.getOpcode() == Instruction::FPToUI ||
2758 I.getOpcode() == Instruction::FPToSI ||
2759 I.getOpcode() == Instruction::PtrToInt)) {
2760 // Make sure we really get a trunc to bool by anding the operand with 1
2766 void CWriter::visitSelectInst(SelectInst &I) {
2768 writeOperand(I.getCondition());
2770 writeOperand(I.getTrueValue());
2772 writeOperand(I.getFalseValue());
2777 void CWriter::lowerIntrinsics(Function &F) {
2778 // This is used to keep track of intrinsics that get generated to a lowered
2779 // function. We must generate the prototypes before the function body which
2780 // will only be expanded on first use (by the loop below).
2781 std::vector<Function*> prototypesToGen;
2783 // Examine all the instructions in this function to find the intrinsics that
2784 // need to be lowered.
2785 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2786 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2787 if (CallInst *CI = dyn_cast<CallInst>(I++))
2788 if (Function *F = CI->getCalledFunction())
2789 switch (F->getIntrinsicID()) {
2790 case Intrinsic::not_intrinsic:
2791 case Intrinsic::memory_barrier:
2792 case Intrinsic::vastart:
2793 case Intrinsic::vacopy:
2794 case Intrinsic::vaend:
2795 case Intrinsic::returnaddress:
2796 case Intrinsic::frameaddress:
2797 case Intrinsic::setjmp:
2798 case Intrinsic::longjmp:
2799 case Intrinsic::prefetch:
2800 case Intrinsic::powi:
2801 case Intrinsic::x86_sse_cmp_ss:
2802 case Intrinsic::x86_sse_cmp_ps:
2803 case Intrinsic::x86_sse2_cmp_sd:
2804 case Intrinsic::x86_sse2_cmp_pd:
2805 case Intrinsic::ppc_altivec_lvsl:
2806 // We directly implement these intrinsics
2809 // If this is an intrinsic that directly corresponds to a GCC
2810 // builtin, we handle it.
2811 const char *BuiltinName = "";
2812 #define GET_GCC_BUILTIN_NAME
2813 #include "llvm/Intrinsics.gen"
2814 #undef GET_GCC_BUILTIN_NAME
2815 // If we handle it, don't lower it.
2816 if (BuiltinName[0]) break;
2818 // All other intrinsic calls we must lower.
2819 Instruction *Before = 0;
2820 if (CI != &BB->front())
2821 Before = prior(BasicBlock::iterator(CI));
2823 IL->LowerIntrinsicCall(CI);
2824 if (Before) { // Move iterator to instruction after call
2829 // If the intrinsic got lowered to another call, and that call has
2830 // a definition then we need to make sure its prototype is emitted
2831 // before any calls to it.
2832 if (CallInst *Call = dyn_cast<CallInst>(I))
2833 if (Function *NewF = Call->getCalledFunction())
2834 if (!NewF->isDeclaration())
2835 prototypesToGen.push_back(NewF);
2840 // We may have collected some prototypes to emit in the loop above.
2841 // Emit them now, before the function that uses them is emitted. But,
2842 // be careful not to emit them twice.
2843 std::vector<Function*>::iterator I = prototypesToGen.begin();
2844 std::vector<Function*>::iterator E = prototypesToGen.end();
2845 for ( ; I != E; ++I) {
2846 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2848 printFunctionSignature(*I, true);
2854 void CWriter::visitCallInst(CallInst &I) {
2855 if (isa<InlineAsm>(I.getOperand(0)))
2856 return visitInlineAsm(I);
2858 bool WroteCallee = false;
2860 // Handle intrinsic function calls first...
2861 if (Function *F = I.getCalledFunction())
2862 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2863 if (visitBuiltinCall(I, ID, WroteCallee))
2866 Value *Callee = I.getCalledValue();
2868 const PointerType *PTy = cast<PointerType>(Callee->getType());
2869 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2871 // If this is a call to a struct-return function, assign to the first
2872 // parameter instead of passing it to the call.
2873 const AttrListPtr &PAL = I.getAttributes();
2874 bool hasByVal = I.hasByValArgument();
2875 bool isStructRet = I.hasStructRetAttr();
2877 writeOperandDeref(I.getOperand(1));
2881 if (I.isTailCall()) Out << " /*tail*/ ";
2884 // If this is an indirect call to a struct return function, we need to cast
2885 // the pointer. Ditto for indirect calls with byval arguments.
2886 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
2888 // GCC is a real PITA. It does not permit codegening casts of functions to
2889 // function pointers if they are in a call (it generates a trap instruction
2890 // instead!). We work around this by inserting a cast to void* in between
2891 // the function and the function pointer cast. Unfortunately, we can't just
2892 // form the constant expression here, because the folder will immediately
2895 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2896 // that void* and function pointers have the same size. :( To deal with this
2897 // in the common case, we handle casts where the number of arguments passed
2900 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2902 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2908 // Ok, just cast the pointer type.
2911 printStructReturnPointerFunctionType(Out, PAL,
2912 cast<PointerType>(I.getCalledValue()->getType()));
2914 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
2916 printType(Out, I.getCalledValue()->getType());
2919 writeOperand(Callee);
2920 if (NeedsCast) Out << ')';
2925 unsigned NumDeclaredParams = FTy->getNumParams();
2927 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2929 if (isStructRet) { // Skip struct return argument.
2934 bool PrintedArg = false;
2935 for (; AI != AE; ++AI, ++ArgNo) {
2936 if (PrintedArg) Out << ", ";
2937 if (ArgNo < NumDeclaredParams &&
2938 (*AI)->getType() != FTy->getParamType(ArgNo)) {
2940 printType(Out, FTy->getParamType(ArgNo),
2941 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
2944 // Check if the argument is expected to be passed by value.
2945 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
2946 writeOperandDeref(*AI);
2954 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
2955 /// if the entire call is handled, return false if it wasn't handled, and
2956 /// optionally set 'WroteCallee' if the callee has already been printed out.
2957 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
2958 bool &WroteCallee) {
2961 // If this is an intrinsic that directly corresponds to a GCC
2962 // builtin, we emit it here.
2963 const char *BuiltinName = "";
2964 Function *F = I.getCalledFunction();
2965 #define GET_GCC_BUILTIN_NAME
2966 #include "llvm/Intrinsics.gen"
2967 #undef GET_GCC_BUILTIN_NAME
2968 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2974 case Intrinsic::memory_barrier:
2975 Out << "__sync_synchronize()";
2977 case Intrinsic::vastart:
2980 Out << "va_start(*(va_list*)";
2981 writeOperand(I.getOperand(1));
2983 // Output the last argument to the enclosing function.
2984 if (I.getParent()->getParent()->arg_empty()) {
2986 raw_string_ostream Msg(msg);
2987 Msg << "The C backend does not currently support zero "
2988 << "argument varargs functions, such as '"
2989 << I.getParent()->getParent()->getName() << "'!";
2990 llvm_report_error(Msg.str());
2992 writeOperand(--I.getParent()->getParent()->arg_end());
2995 case Intrinsic::vaend:
2996 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2997 Out << "0; va_end(*(va_list*)";
2998 writeOperand(I.getOperand(1));
3001 Out << "va_end(*(va_list*)0)";
3004 case Intrinsic::vacopy:
3006 Out << "va_copy(*(va_list*)";
3007 writeOperand(I.getOperand(1));
3008 Out << ", *(va_list*)";
3009 writeOperand(I.getOperand(2));
3012 case Intrinsic::returnaddress:
3013 Out << "__builtin_return_address(";
3014 writeOperand(I.getOperand(1));
3017 case Intrinsic::frameaddress:
3018 Out << "__builtin_frame_address(";
3019 writeOperand(I.getOperand(1));
3022 case Intrinsic::powi:
3023 Out << "__builtin_powi(";
3024 writeOperand(I.getOperand(1));
3026 writeOperand(I.getOperand(2));
3029 case Intrinsic::setjmp:
3030 Out << "setjmp(*(jmp_buf*)";
3031 writeOperand(I.getOperand(1));
3034 case Intrinsic::longjmp:
3035 Out << "longjmp(*(jmp_buf*)";
3036 writeOperand(I.getOperand(1));
3038 writeOperand(I.getOperand(2));
3041 case Intrinsic::prefetch:
3042 Out << "LLVM_PREFETCH((const void *)";
3043 writeOperand(I.getOperand(1));
3045 writeOperand(I.getOperand(2));
3047 writeOperand(I.getOperand(3));
3050 case Intrinsic::stacksave:
3051 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3052 // to work around GCC bugs (see PR1809).
3053 Out << "0; *((void**)&" << GetValueName(&I)
3054 << ") = __builtin_stack_save()";
3056 case Intrinsic::x86_sse_cmp_ss:
3057 case Intrinsic::x86_sse_cmp_ps:
3058 case Intrinsic::x86_sse2_cmp_sd:
3059 case Intrinsic::x86_sse2_cmp_pd:
3061 printType(Out, I.getType());
3063 // Multiple GCC builtins multiplex onto this intrinsic.
3064 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
3065 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
3066 case 0: Out << "__builtin_ia32_cmpeq"; break;
3067 case 1: Out << "__builtin_ia32_cmplt"; break;
3068 case 2: Out << "__builtin_ia32_cmple"; break;
3069 case 3: Out << "__builtin_ia32_cmpunord"; break;
3070 case 4: Out << "__builtin_ia32_cmpneq"; break;
3071 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3072 case 6: Out << "__builtin_ia32_cmpnle"; break;
3073 case 7: Out << "__builtin_ia32_cmpord"; break;
3075 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3079 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3085 writeOperand(I.getOperand(1));
3087 writeOperand(I.getOperand(2));
3090 case Intrinsic::ppc_altivec_lvsl:
3092 printType(Out, I.getType());
3094 Out << "__builtin_altivec_lvsl(0, (void*)";
3095 writeOperand(I.getOperand(1));
3101 //This converts the llvm constraint string to something gcc is expecting.
3102 //TODO: work out platform independent constraints and factor those out
3103 // of the per target tables
3104 // handle multiple constraint codes
3105 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
3106 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3108 // Grab the translation table from MCAsmInfo if it exists.
3109 const MCAsmInfo *TargetAsm;
3110 std::string Triple = TheModule->getTargetTriple();
3112 Triple = llvm::sys::getHostTriple();
3115 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3116 TargetAsm = Match->createAsmInfo(Triple);
3120 const char *const *table = TargetAsm->getAsmCBE();
3122 // Search the translation table if it exists.
3123 for (int i = 0; table && table[i]; i += 2)
3124 if (c.Codes[0] == table[i]) {
3129 // Default is identity.
3134 //TODO: import logic from AsmPrinter.cpp
3135 static std::string gccifyAsm(std::string asmstr) {
3136 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3137 if (asmstr[i] == '\n')
3138 asmstr.replace(i, 1, "\\n");
3139 else if (asmstr[i] == '\t')
3140 asmstr.replace(i, 1, "\\t");
3141 else if (asmstr[i] == '$') {
3142 if (asmstr[i + 1] == '{') {
3143 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3144 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3145 std::string n = "%" +
3146 asmstr.substr(a + 1, b - a - 1) +
3147 asmstr.substr(i + 2, a - i - 2);
3148 asmstr.replace(i, b - i + 1, n);
3151 asmstr.replace(i, 1, "%");
3153 else if (asmstr[i] == '%')//grr
3154 { asmstr.replace(i, 1, "%%"); ++i;}
3159 //TODO: assumptions about what consume arguments from the call are likely wrong
3160 // handle communitivity
3161 void CWriter::visitInlineAsm(CallInst &CI) {
3162 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
3163 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
3165 std::vector<std::pair<Value*, int> > ResultVals;
3166 if (CI.getType() == Type::getVoidTy(CI.getContext()))
3168 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3169 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3170 ResultVals.push_back(std::make_pair(&CI, (int)i));
3172 ResultVals.push_back(std::make_pair(&CI, -1));
3175 // Fix up the asm string for gcc and emit it.
3176 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3179 unsigned ValueCount = 0;
3180 bool IsFirst = true;
3182 // Convert over all the output constraints.
3183 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3184 E = Constraints.end(); I != E; ++I) {
3186 if (I->Type != InlineAsm::isOutput) {
3188 continue; // Ignore non-output constraints.
3191 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3192 std::string C = InterpretASMConstraint(*I);
3193 if (C.empty()) continue;
3204 if (ValueCount < ResultVals.size()) {
3205 DestVal = ResultVals[ValueCount].first;
3206 DestValNo = ResultVals[ValueCount].second;
3208 DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3210 if (I->isEarlyClobber)
3213 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3214 if (DestValNo != -1)
3215 Out << ".field" << DestValNo; // Multiple retvals.
3221 // Convert over all the input constraints.
3225 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3226 E = Constraints.end(); I != E; ++I) {
3227 if (I->Type != InlineAsm::isInput) {
3229 continue; // Ignore non-input constraints.
3232 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3233 std::string C = InterpretASMConstraint(*I);
3234 if (C.empty()) continue;
3241 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3242 Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
3244 Out << "\"" << C << "\"(";
3246 writeOperand(SrcVal);
3248 writeOperandDeref(SrcVal);
3252 // Convert over the clobber constraints.
3254 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
3255 E = Constraints.end(); I != E; ++I) {
3256 if (I->Type != InlineAsm::isClobber)
3257 continue; // Ignore non-input constraints.
3259 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3260 std::string C = InterpretASMConstraint(*I);
3261 if (C.empty()) continue;
3268 Out << '\"' << C << '"';
3274 void CWriter::visitAllocaInst(AllocaInst &I) {
3276 printType(Out, I.getType());
3277 Out << ") alloca(sizeof(";
3278 printType(Out, I.getType()->getElementType());
3280 if (I.isArrayAllocation()) {
3282 writeOperand(I.getOperand(0));
3287 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
3288 gep_type_iterator E, bool Static) {
3290 // If there are no indices, just print out the pointer.
3296 // Find out if the last index is into a vector. If so, we have to print this
3297 // specially. Since vectors can't have elements of indexable type, only the
3298 // last index could possibly be of a vector element.
3299 const VectorType *LastIndexIsVector = 0;
3301 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3302 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
3307 // If the last index is into a vector, we can't print it as &a[i][j] because
3308 // we can't index into a vector with j in GCC. Instead, emit this as
3309 // (((float*)&a[i])+j)
3310 if (LastIndexIsVector) {
3312 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3318 // If the first index is 0 (very typical) we can do a number of
3319 // simplifications to clean up the code.
3320 Value *FirstOp = I.getOperand();
3321 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3322 // First index isn't simple, print it the hard way.
3325 ++I; // Skip the zero index.
3327 // Okay, emit the first operand. If Ptr is something that is already address
3328 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3329 if (isAddressExposed(Ptr)) {
3330 writeOperandInternal(Ptr, Static);
3331 } else if (I != E && (*I)->isStructTy()) {
3332 // If we didn't already emit the first operand, see if we can print it as
3333 // P->f instead of "P[0].f"
3335 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3336 ++I; // eat the struct index as well.
3338 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3345 for (; I != E; ++I) {
3346 if ((*I)->isStructTy()) {
3347 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3348 } else if ((*I)->isArrayTy()) {
3350 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3352 } else if (!(*I)->isVectorTy()) {
3354 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3357 // If the last index is into a vector, then print it out as "+j)". This
3358 // works with the 'LastIndexIsVector' code above.
3359 if (isa<Constant>(I.getOperand()) &&
3360 cast<Constant>(I.getOperand())->isNullValue()) {
3361 Out << "))"; // avoid "+0".
3364 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3372 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3373 bool IsVolatile, unsigned Alignment) {
3375 bool IsUnaligned = Alignment &&
3376 Alignment < TD->getABITypeAlignment(OperandType);
3380 if (IsVolatile || IsUnaligned) {
3383 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3384 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3387 if (IsVolatile) Out << "volatile ";
3393 writeOperand(Operand);
3395 if (IsVolatile || IsUnaligned) {
3402 void CWriter::visitLoadInst(LoadInst &I) {
3403 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3408 void CWriter::visitStoreInst(StoreInst &I) {
3409 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3410 I.isVolatile(), I.getAlignment());
3412 Value *Operand = I.getOperand(0);
3413 Constant *BitMask = 0;
3414 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3415 if (!ITy->isPowerOf2ByteWidth())
3416 // We have a bit width that doesn't match an even power-of-2 byte
3417 // size. Consequently we must & the value with the type's bit mask
3418 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
3421 writeOperand(Operand);
3424 printConstant(BitMask, false);
3429 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3430 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
3431 gep_type_end(I), false);
3434 void CWriter::visitVAArgInst(VAArgInst &I) {
3435 Out << "va_arg(*(va_list*)";
3436 writeOperand(I.getOperand(0));
3438 printType(Out, I.getType());
3442 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3443 const Type *EltTy = I.getType()->getElementType();
3444 writeOperand(I.getOperand(0));
3447 printType(Out, PointerType::getUnqual(EltTy));
3448 Out << ")(&" << GetValueName(&I) << "))[";
3449 writeOperand(I.getOperand(2));
3451 writeOperand(I.getOperand(1));
3455 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3456 // We know that our operand is not inlined.
3459 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3460 printType(Out, PointerType::getUnqual(EltTy));
3461 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3462 writeOperand(I.getOperand(1));
3466 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3468 printType(Out, SVI.getType());
3470 const VectorType *VT = SVI.getType();
3471 unsigned NumElts = VT->getNumElements();
3472 const Type *EltTy = VT->getElementType();
3474 for (unsigned i = 0; i != NumElts; ++i) {
3476 int SrcVal = SVI.getMaskValue(i);
3477 if ((unsigned)SrcVal >= NumElts*2) {
3478 Out << " 0/*undef*/ ";
3480 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3481 if (isa<Instruction>(Op)) {
3482 // Do an extractelement of this value from the appropriate input.
3484 printType(Out, PointerType::getUnqual(EltTy));
3485 Out << ")(&" << GetValueName(Op)
3486 << "))[" << (SrcVal & (NumElts-1)) << "]";
3487 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3490 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
3499 void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3500 // Start by copying the entire aggregate value into the result variable.
3501 writeOperand(IVI.getOperand(0));
3504 // Then do the insert to update the field.
3505 Out << GetValueName(&IVI);
3506 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3508 const Type *IndexedTy =
3509 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3510 if (IndexedTy->isArrayTy())
3511 Out << ".array[" << *i << "]";
3513 Out << ".field" << *i;
3516 writeOperand(IVI.getOperand(1));
3519 void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3521 if (isa<UndefValue>(EVI.getOperand(0))) {
3523 printType(Out, EVI.getType());
3524 Out << ") 0/*UNDEF*/";
3526 Out << GetValueName(EVI.getOperand(0));
3527 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3529 const Type *IndexedTy =
3530 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3531 if (IndexedTy->isArrayTy())
3532 Out << ".array[" << *i << "]";
3534 Out << ".field" << *i;
3540 //===----------------------------------------------------------------------===//
3541 // External Interface declaration
3542 //===----------------------------------------------------------------------===//
3544 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
3545 formatted_raw_ostream &o,
3546 CodeGenFileType FileType,
3547 CodeGenOpt::Level OptLevel) {
3548 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
3550 PM.add(createGCLoweringPass());
3551 PM.add(createLowerInvokePass());
3552 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3553 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3554 PM.add(new CWriter(o));
3555 PM.add(createGCInfoDeleter());