1 //===-- MSILWriter.cpp - Library for converting LLVM code to MSIL ---------===//
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 MSIL code.
12 //===----------------------------------------------------------------------===//
14 #include "MSILWriter.h"
15 #include "llvm/CallingConv.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Intrinsics.h"
18 #include "llvm/IntrinsicInst.h"
19 #include "llvm/TypeSymbolTable.h"
20 #include "llvm/Analysis/ConstantsScanner.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/InstVisitor.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Target/TargetRegistry.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/Passes.h"
32 // TargetMachine for the MSIL
33 struct MSILTarget : public TargetMachine {
34 MSILTarget(const Target &T, const std::string &TT, const std::string &FS)
37 virtual bool WantsWholeFile() const { return true; }
38 virtual bool addPassesToEmitWholeFile(PassManager &PM,
39 formatted_raw_ostream &Out,
40 CodeGenFileType FileType,
41 CodeGenOpt::Level OptLevel);
43 virtual const TargetData *getTargetData() const { return 0; }
47 extern "C" void LLVMInitializeMSILTarget() {
48 // Register the target.
49 RegisterTargetMachine<MSILTarget> X(TheMSILTarget);
52 bool MSILModule::runOnModule(Module &M) {
54 TD = &getAnalysis<TargetData>();
57 TypeSymbolTable& Table = M.getTypeSymbolTable();
58 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
59 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
60 if (!I->second->isStructTy() && !I->second->isOpaqueTy())
63 std::set<const Type *>::iterator T = Types.find(I->second);
72 // Find unnamed types.
73 unsigned RenameCounter = 0;
74 for (std::set<const Type *>::const_iterator I = Types.begin(),
75 E = Types.end(); I!=E; ++I)
76 if (const StructType *STy = dyn_cast<StructType>(*I)) {
77 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
81 // Pointer for FunctionPass.
82 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
86 char MSILModule::ID = 0;
87 char MSILWriter::ID = 0;
89 bool MSILWriter::runOnFunction(Function &F) {
90 if (F.isDeclaration()) return false;
92 // Do not codegen any 'available_externally' functions at all, they have
93 // definitions outside the translation unit.
94 if (F.hasAvailableExternallyLinkage())
97 LInfo = &getAnalysis<LoopInfo>();
103 bool MSILWriter::doInitialization(Module &M) {
105 Out << ".assembly extern mscorlib {}\n";
106 Out << ".assembly MSIL {}\n\n";
107 Out << "// External\n";
109 Out << "// Declarations\n";
110 printDeclarations(M.getTypeSymbolTable());
111 Out << "// Definitions\n";
112 printGlobalVariables();
113 Out << "// Startup code\n";
114 printModuleStartup();
119 bool MSILWriter::doFinalization(Module &M) {
124 void MSILWriter::printModuleStartup() {
126 ".method static public int32 $MSIL_Startup() {\n"
128 "\t.locals (native int i)\n"
129 "\t.locals (native int argc)\n"
130 "\t.locals (native int ptr)\n"
131 "\t.locals (void* argv)\n"
132 "\t.locals (string[] args)\n"
133 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
140 printPtrLoad(TD->getPointerSize());
155 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
156 "StringToHGlobalAnsi(string)\n"
160 printPtrLoad(TD->getPointerSize());
172 "\tcall void $MSIL_Init()\n";
174 // Call user 'main' function.
175 const Function* F = ModulePtr->getFunction("main");
176 if (!F || F->isDeclaration()) {
177 Out << "\tldc.i4.0\n\tret\n}\n";
181 std::string Args("");
182 Function::const_arg_iterator Arg1,Arg2;
184 switch (F->arg_size()) {
189 Arg1 = F->arg_begin();
190 if (Arg1->getType()->isIntegerTy()) {
191 Out << "\tldloc\targc\n";
192 Args = getTypeName(Arg1->getType());
197 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
198 if (Arg1->getType()->isIntegerTy() &&
199 Arg2->getType()->getTypeID() == Type::PointerTyID) {
200 Out << "\tldloc\targc\n\tldloc\targv\n";
201 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
209 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
210 if (BadSig || (!F->getReturnType()->isIntegerTy() && !RetVoid)) {
211 Out << "\tldc.i4.0\n";
213 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
214 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
216 Out << "\tldc.i4.0\n";
218 Out << "\tconv.i4\n";
223 bool MSILWriter::isZeroValue(const Value* V) {
224 if (const Constant *C = dyn_cast<Constant>(V))
225 return C->isNullValue();
230 std::string MSILWriter::getValueName(const Value* V) {
232 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
233 Name = GV->getName();
235 unsigned &No = AnonValueNumbers[V];
236 if (No == 0) No = ++NextAnonValueNumber;
237 Name = "tmp" + utostr(No);
240 // Name into the quotes allow control and space characters.
245 std::string MSILWriter::getLabelName(const std::string& Name) {
246 if (Name.find('.')!=std::string::npos) {
247 std::string Tmp(Name);
248 // Replace unaccepable characters in the label name.
249 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
250 if (*I=='.') *I = '@';
257 std::string MSILWriter::getLabelName(const Value* V) {
259 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
260 Name = GV->getName();
262 unsigned &No = AnonValueNumbers[V];
263 if (No == 0) No = ++NextAnonValueNumber;
264 Name = "tmp" + utostr(No);
267 return getLabelName(Name);
271 std::string MSILWriter::getConvModopt(CallingConv::ID CallingConvID) {
272 switch (CallingConvID) {
274 case CallingConv::Cold:
275 case CallingConv::Fast:
276 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
277 case CallingConv::X86_FastCall:
278 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
279 case CallingConv::X86_StdCall:
280 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
282 errs() << "CallingConvID = " << CallingConvID << '\n';
283 llvm_unreachable("Unsupported calling convention");
285 return ""; // Not reached
289 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
290 std::string Tmp = "";
291 const Type* ElemTy = Ty;
292 assert(Ty->getTypeID()==TyID && "Invalid type passed");
293 // Walk trought array element types.
295 // Multidimensional array.
296 if (ElemTy->getTypeID()==TyID) {
297 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
298 Tmp += utostr(ATy->getNumElements());
299 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
300 Tmp += utostr(VTy->getNumElements());
301 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
303 // Base element type found.
304 if (ElemTy->getTypeID()!=TyID) break;
307 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
311 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
312 unsigned NumBits = 0;
313 switch (Ty->getTypeID()) {
316 case Type::IntegerTyID:
317 NumBits = getBitWidth(Ty);
321 return "unsigned int"+utostr(NumBits)+" ";
322 return "int"+utostr(NumBits)+" ";
323 case Type::FloatTyID:
325 case Type::DoubleTyID:
328 errs() << "Type = " << *Ty << '\n';
329 llvm_unreachable("Invalid primitive type");
331 return ""; // Not reached
335 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
337 if (Ty->isPrimitiveType() || Ty->isIntegerTy())
338 return getPrimitiveTypeName(Ty,isSigned);
339 // FIXME: "OpaqueType" support
340 switch (Ty->getTypeID()) {
341 case Type::PointerTyID:
343 case Type::StructTyID:
345 return ModulePtr->getTypeName(Ty);
346 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
347 case Type::ArrayTyID:
349 return getArrayTypeName(Ty->getTypeID(),Ty);
350 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
351 case Type::VectorTyID:
353 return getArrayTypeName(Ty->getTypeID(),Ty);
354 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
356 errs() << "Type = " << *Ty << '\n';
357 llvm_unreachable("Invalid type in getTypeName()");
359 return ""; // Not reached
363 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
365 if (isa<Argument>(V))
368 else if (const Function* F = dyn_cast<Function>(V))
369 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
371 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
372 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
374 else if (isa<Constant>(V))
375 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
381 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
383 unsigned NumBits = 0;
384 switch (Ty->getTypeID()) {
385 // Integer constant, expanding for stack operations.
386 case Type::IntegerTyID:
387 NumBits = getBitWidth(Ty);
388 // Expand integer value to "int32" or "int64".
389 if (Expand) return (NumBits<=32 ? "i4" : "i8");
390 if (NumBits==1) return "i1";
391 return (isSigned ? "i" : "u")+utostr(NumBits/8);
393 case Type::FloatTyID:
395 case Type::DoubleTyID:
397 case Type::PointerTyID:
398 return "i"+utostr(TD->getTypeAllocSize(Ty));
400 errs() << "TypeID = " << Ty->getTypeID() << '\n';
401 llvm_unreachable("Invalid type in TypeToPostfix()");
403 return ""; // Not reached
407 void MSILWriter::printConvToPtr() {
408 switch (ModulePtr->getPointerSize()) {
409 case Module::Pointer32:
410 printSimpleInstruction("conv.u4");
412 case Module::Pointer64:
413 printSimpleInstruction("conv.u8");
416 llvm_unreachable("Module use not supporting pointer size");
421 void MSILWriter::printPtrLoad(uint64_t N) {
422 switch (ModulePtr->getPointerSize()) {
423 case Module::Pointer32:
424 printSimpleInstruction("ldc.i4",utostr(N).c_str());
425 // FIXME: Need overflow test?
427 errs() << "Value = " << utostr(N) << '\n';
428 llvm_unreachable("32-bit pointer overflowed");
431 case Module::Pointer64:
432 printSimpleInstruction("ldc.i8",utostr(N).c_str());
435 llvm_unreachable("Module use not supporting pointer size");
440 void MSILWriter::printValuePtrLoad(const Value* V) {
446 void MSILWriter::printConstLoad(const Constant* C) {
447 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
449 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
450 if (CInt->isMinValue(true))
451 Out << CInt->getSExtValue();
453 Out << CInt->getZExtValue();
454 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
458 if (FP->getType()->getTypeID()==Type::FloatTyID) {
459 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
462 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
465 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
466 } else if (isa<UndefValue>(C)) {
467 // Undefined constant value = NULL.
470 errs() << "Constant = " << *C << '\n';
471 llvm_unreachable("Invalid constant value");
477 void MSILWriter::printValueLoad(const Value* V) {
478 MSILWriter::ValueType Location = getValueLocation(V);
480 // Global variable or function address.
483 if (const Function* F = dyn_cast<Function>(V)) {
484 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
485 printSimpleInstruction("ldftn",
486 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
489 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
490 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
491 Tmp = "void* "+getValueName(V);
492 printSimpleInstruction("ldsfld",Tmp.c_str());
494 Tmp = getTypeName(ElemTy)+getValueName(V);
495 printSimpleInstruction("ldsflda",Tmp.c_str());
499 // Function argument.
501 printSimpleInstruction("ldarg",getValueName(V).c_str());
503 // Local function variable.
505 printSimpleInstruction("ldloc",getValueName(V).c_str());
509 if (isa<ConstantPointerNull>(V))
512 printConstLoad(cast<Constant>(V));
514 // Constant expression.
516 printConstantExpr(cast<ConstantExpr>(V));
519 errs() << "Value = " << *V << '\n';
520 llvm_unreachable("Invalid value location");
525 void MSILWriter::printValueSave(const Value* V) {
526 switch (getValueLocation(V)) {
528 printSimpleInstruction("starg",getValueName(V).c_str());
531 printSimpleInstruction("stloc",getValueName(V).c_str());
534 errs() << "Value = " << *V << '\n';
535 llvm_unreachable("Invalid value location");
540 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
541 const Value* Right) {
542 printValueLoad(Left);
543 printValueLoad(Right);
544 Out << '\t' << Name << '\n';
548 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
550 Out << '\t' << Inst << '\t' << Operand << '\n';
552 Out << '\t' << Inst << '\n';
556 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
557 for (BasicBlock::const_iterator I = Dst->begin(); isa<PHINode>(I); ++I) {
558 const PHINode* Phi = cast<PHINode>(I);
559 const Value* Val = Phi->getIncomingValueForBlock(Src);
560 if (isa<UndefValue>(Val)) continue;
567 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
568 const BasicBlock* TrueBB,
569 const BasicBlock* FalseBB) {
570 if (TrueBB==FalseBB) {
571 // "TrueBB" and "FalseBB" destination equals
572 printPHICopy(CurrBB,TrueBB);
573 printSimpleInstruction("pop");
574 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
575 } else if (FalseBB==NULL) {
576 // If "FalseBB" not used the jump have condition
577 printPHICopy(CurrBB,TrueBB);
578 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
579 } else if (TrueBB==NULL) {
580 // If "TrueBB" not used the jump is unconditional
581 printPHICopy(CurrBB,FalseBB);
582 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
584 // Copy PHI instructions for each block
585 std::string TmpLabel;
586 // Print PHI instructions for "TrueBB"
587 if (isa<PHINode>(TrueBB->begin())) {
588 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
589 printSimpleInstruction("brtrue",TmpLabel.c_str());
591 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
593 // Print PHI instructions for "FalseBB"
594 if (isa<PHINode>(FalseBB->begin())) {
595 printPHICopy(CurrBB,FalseBB);
596 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
598 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
600 if (isa<PHINode>(TrueBB->begin())) {
601 // Handle "TrueBB" PHI Copy
602 Out << TmpLabel << ":\n";
603 printPHICopy(CurrBB,TrueBB);
604 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
610 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
611 if (Inst->isUnconditional()) {
612 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
614 printValueLoad(Inst->getCondition());
615 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
616 Inst->getSuccessor(1));
621 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
622 const Value* VFalse) {
623 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
624 printValueLoad(VTrue);
625 printValueLoad(Cond);
626 printSimpleInstruction("brtrue",TmpLabel.c_str());
627 printSimpleInstruction("pop");
628 printValueLoad(VFalse);
629 Out << TmpLabel << ":\n";
633 void MSILWriter::printIndirectLoad(const Value* V) {
634 const Type* Ty = V->getType();
636 if (const PointerType* P = dyn_cast<PointerType>(Ty))
637 Ty = P->getElementType();
638 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
639 printSimpleInstruction(Tmp.c_str());
643 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
646 printIndirectSave(Val->getType());
650 void MSILWriter::printIndirectSave(const Type* Ty) {
651 // Instruction need signed postfix for any type.
652 std::string postfix = getTypePostfix(Ty, false);
653 if (*postfix.begin()=='u') *postfix.begin() = 'i';
654 postfix = "stind."+postfix;
655 printSimpleInstruction(postfix.c_str());
659 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
660 const Type* Ty, const Type* SrcTy) {
665 case Instruction::SExt:
666 // If sign extending int, convert first from unsigned to signed
667 // with the same bit size - because otherwise we will loose the sign.
669 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
670 printSimpleInstruction(Tmp.c_str());
673 case Instruction::SIToFP:
674 case Instruction::FPToSI:
675 Tmp = "conv."+getTypePostfix(Ty,false,true);
676 printSimpleInstruction(Tmp.c_str());
679 case Instruction::FPTrunc:
680 case Instruction::FPExt:
681 case Instruction::UIToFP:
682 case Instruction::Trunc:
683 case Instruction::ZExt:
684 case Instruction::FPToUI:
685 case Instruction::PtrToInt:
686 case Instruction::IntToPtr:
687 Tmp = "conv."+getTypePostfix(Ty,false);
688 printSimpleInstruction(Tmp.c_str());
691 case Instruction::BitCast:
692 // FIXME: meaning that ld*/st* instruction do not change data format.
695 errs() << "Opcode = " << Op << '\n';
696 llvm_unreachable("Invalid conversion instruction");
701 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
702 gep_type_iterator E) {
705 printValuePtrLoad(V);
706 // Calculate element offset.
709 const Value* IndexValue = I.getOperand();
710 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
711 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
712 // Offset is the sum of all previous structure fields.
713 for (uint64_t F = 0; F<FieldIndex; ++F)
714 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
716 printSimpleInstruction("add");
718 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
719 Size = TD->getTypeAllocSize(SeqTy->getElementType());
721 Size = TD->getTypeAllocSize(*I);
723 // Add offset of current element to stack top.
724 if (!isZeroValue(IndexValue)) {
725 // Constant optimization.
726 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
727 if (C->getValue().isNegative()) {
728 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
729 printSimpleInstruction("sub");
732 printPtrLoad(C->getZExtValue()*Size);
735 printValuePtrLoad(IndexValue);
736 printSimpleInstruction("mul");
738 printSimpleInstruction("add");
744 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
745 const Instruction* Inst,
748 if (Ty->isVarArg()) Tmp += "vararg ";
749 // Name and return type.
750 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
751 // Function argument type list.
752 unsigned NumParams = Ty->getNumParams();
753 for (unsigned I = 0; I!=NumParams; ++I) {
754 if (I!=0) Tmp += ",";
755 Tmp += getTypeName(Ty->getParamType(I));
757 // CLR needs to know the exact amount of parameters received by vararg
758 // function, because caller cleans the stack.
759 if (Ty->isVarArg() && Inst) {
760 // Origin to function arguments in "CallInst" or "InvokeInst".
761 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
762 // Print variable argument types.
763 unsigned NumOperands = Inst->getNumOperands()-Org;
764 if (NumParams<NumOperands) {
765 if (NumParams!=0) Tmp += ", ";
767 for (unsigned J = NumParams; J!=NumOperands; ++J) {
768 if (J!=NumParams) Tmp += ", ";
769 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
777 void MSILWriter::printFunctionCall(const Value* FnVal,
778 const Instruction* Inst) {
779 // Get function calling convention.
780 std::string Name = "";
781 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
782 Name = getConvModopt(Call->getCallingConv());
783 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
784 Name = getConvModopt(Invoke->getCallingConv());
786 errs() << "Instruction = " << Inst->getName() << '\n';
787 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
789 if (const Function* F = dyn_cast<Function>(FnVal)) {
791 Name += getValueName(F);
792 printSimpleInstruction("call",
793 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
795 // Indirect function call.
796 const PointerType* PTy = cast<PointerType>(FnVal->getType());
797 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
798 // Load function address.
799 printValueLoad(FnVal);
800 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
805 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
807 switch (Inst->getIntrinsicID()) {
808 case Intrinsic::vastart:
809 Name = getValueName(Inst->getOperand(1));
810 Name.insert(Name.length()-1,"$valist");
811 // Obtain the argument handle.
812 printSimpleInstruction("ldloca",Name.c_str());
813 printSimpleInstruction("arglist");
814 printSimpleInstruction("call",
815 "instance void [mscorlib]System.ArgIterator::.ctor"
816 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
817 // Save as pointer type "void*"
818 printValueLoad(Inst->getOperand(1));
819 printSimpleInstruction("ldloca",Name.c_str());
820 printIndirectSave(PointerType::getUnqual(
821 IntegerType::get(Inst->getContext(), 8)));
823 case Intrinsic::vaend:
824 // Close argument list handle.
825 printIndirectLoad(Inst->getOperand(1));
826 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
828 case Intrinsic::vacopy:
829 // Copy "ArgIterator" valuetype.
830 printIndirectLoad(Inst->getOperand(1));
831 printIndirectLoad(Inst->getOperand(2));
832 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
835 errs() << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
836 llvm_unreachable("Invalid intrinsic function");
841 void MSILWriter::printCallInstruction(const Instruction* Inst) {
842 if (isa<IntrinsicInst>(Inst)) {
843 // Handle intrinsic function.
844 printIntrinsicCall(cast<IntrinsicInst>(Inst));
846 // Load arguments to stack and call function.
847 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
848 printValueLoad(Inst->getOperand(I));
849 printFunctionCall(Inst->getOperand(0),Inst);
854 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
855 const Value* Right) {
857 case ICmpInst::ICMP_EQ:
858 printBinaryInstruction("ceq",Left,Right);
860 case ICmpInst::ICMP_NE:
861 // Emulate = not neg (Op1 eq Op2)
862 printBinaryInstruction("ceq",Left,Right);
863 printSimpleInstruction("neg");
864 printSimpleInstruction("not");
866 case ICmpInst::ICMP_ULE:
867 case ICmpInst::ICMP_SLE:
868 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
869 printBinaryInstruction("ceq",Left,Right);
870 if (Predicate==ICmpInst::ICMP_ULE)
871 printBinaryInstruction("clt.un",Left,Right);
873 printBinaryInstruction("clt",Left,Right);
874 printSimpleInstruction("or");
876 case ICmpInst::ICMP_UGE:
877 case ICmpInst::ICMP_SGE:
878 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
879 printBinaryInstruction("ceq",Left,Right);
880 if (Predicate==ICmpInst::ICMP_UGE)
881 printBinaryInstruction("cgt.un",Left,Right);
883 printBinaryInstruction("cgt",Left,Right);
884 printSimpleInstruction("or");
886 case ICmpInst::ICMP_ULT:
887 printBinaryInstruction("clt.un",Left,Right);
889 case ICmpInst::ICMP_SLT:
890 printBinaryInstruction("clt",Left,Right);
892 case ICmpInst::ICMP_UGT:
893 printBinaryInstruction("cgt.un",Left,Right);
895 case ICmpInst::ICMP_SGT:
896 printBinaryInstruction("cgt",Left,Right);
899 errs() << "Predicate = " << Predicate << '\n';
900 llvm_unreachable("Invalid icmp predicate");
905 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
906 const Value* Right) {
907 // FIXME: Correct comparison
908 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
910 case FCmpInst::FCMP_UGT:
911 // X > Y || llvm_fcmp_uno(X, Y)
912 printBinaryInstruction("cgt",Left,Right);
913 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
914 printSimpleInstruction("or");
916 case FCmpInst::FCMP_OGT:
918 printBinaryInstruction("cgt",Left,Right);
920 case FCmpInst::FCMP_UGE:
921 // X >= Y || llvm_fcmp_uno(X, Y)
922 printBinaryInstruction("ceq",Left,Right);
923 printBinaryInstruction("cgt",Left,Right);
924 printSimpleInstruction("or");
925 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
926 printSimpleInstruction("or");
928 case FCmpInst::FCMP_OGE:
930 printBinaryInstruction("ceq",Left,Right);
931 printBinaryInstruction("cgt",Left,Right);
932 printSimpleInstruction("or");
934 case FCmpInst::FCMP_ULT:
935 // X < Y || llvm_fcmp_uno(X, Y)
936 printBinaryInstruction("clt",Left,Right);
937 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
938 printSimpleInstruction("or");
940 case FCmpInst::FCMP_OLT:
942 printBinaryInstruction("clt",Left,Right);
944 case FCmpInst::FCMP_ULE:
945 // X <= Y || llvm_fcmp_uno(X, Y)
946 printBinaryInstruction("ceq",Left,Right);
947 printBinaryInstruction("clt",Left,Right);
948 printSimpleInstruction("or");
949 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
950 printSimpleInstruction("or");
952 case FCmpInst::FCMP_OLE:
954 printBinaryInstruction("ceq",Left,Right);
955 printBinaryInstruction("clt",Left,Right);
956 printSimpleInstruction("or");
958 case FCmpInst::FCMP_UEQ:
959 // X == Y || llvm_fcmp_uno(X, Y)
960 printBinaryInstruction("ceq",Left,Right);
961 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
962 printSimpleInstruction("or");
964 case FCmpInst::FCMP_OEQ:
966 printBinaryInstruction("ceq",Left,Right);
968 case FCmpInst::FCMP_UNE:
970 printBinaryInstruction("ceq",Left,Right);
971 printSimpleInstruction("neg");
972 printSimpleInstruction("not");
974 case FCmpInst::FCMP_ONE:
975 // X != Y && llvm_fcmp_ord(X, Y)
976 printBinaryInstruction("ceq",Left,Right);
977 printSimpleInstruction("not");
979 case FCmpInst::FCMP_ORD:
980 // return X == X && Y == Y
981 printBinaryInstruction("ceq",Left,Left);
982 printBinaryInstruction("ceq",Right,Right);
983 printSimpleInstruction("or");
985 case FCmpInst::FCMP_UNO:
987 printBinaryInstruction("ceq",Left,Left);
988 printSimpleInstruction("not");
989 printBinaryInstruction("ceq",Right,Right);
990 printSimpleInstruction("not");
991 printSimpleInstruction("or");
994 llvm_unreachable("Illegal FCmp predicate");
999 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1000 std::string Label = "leave$normal_"+utostr(getUniqID());
1003 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1004 printValueLoad(Inst->getOperand(I));
1005 // Print call instruction
1006 printFunctionCall(Inst->getOperand(0),Inst);
1007 // Save function result and leave "try" block
1008 printValueSave(Inst);
1009 printSimpleInstruction("leave",Label.c_str());
1011 Out << "catch [mscorlib]System.Exception {\n";
1012 // Redirect to unwind block
1013 printSimpleInstruction("pop");
1014 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1015 Out << "}\n" << Label << ":\n";
1016 // Redirect to continue block
1017 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1021 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1022 // FIXME: Emulate with IL "switch" instruction
1023 // Emulate = if () else if () else if () else ...
1024 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1025 printValueLoad(Inst->getCondition());
1026 printValueLoad(Inst->getCaseValue(I));
1027 printSimpleInstruction("ceq");
1028 // Condition jump to successor block
1029 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1031 // Jump to default block
1032 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1036 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1037 printIndirectLoad(Inst->getOperand(0));
1038 printSimpleInstruction("call",
1039 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1040 printSimpleInstruction("refanyval","void*");
1042 "ldind."+getTypePostfix(PointerType::getUnqual(
1043 IntegerType::get(Inst->getContext(), 8)),false);
1044 printSimpleInstruction(Name.c_str());
1048 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
1049 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
1050 // Constant optimization.
1051 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1052 printPtrLoad(CInt->getZExtValue()*Size);
1055 printValueLoad(Inst->getOperand(0));
1056 printSimpleInstruction("mul");
1058 printSimpleInstruction("localloc");
1062 void MSILWriter::printInstruction(const Instruction* Inst) {
1063 const Value *Left = 0, *Right = 0;
1064 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1065 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1066 // Print instruction
1067 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
1068 switch (Inst->getOpcode()) {
1070 case Instruction::Ret:
1071 if (Inst->getNumOperands()) {
1072 printValueLoad(Left);
1073 printSimpleInstruction("ret");
1075 printSimpleInstruction("ret");
1077 case Instruction::Br:
1078 printBranchInstruction(cast<BranchInst>(Inst));
1081 case Instruction::Add:
1082 case Instruction::FAdd:
1083 printBinaryInstruction("add",Left,Right);
1085 case Instruction::Sub:
1086 case Instruction::FSub:
1087 printBinaryInstruction("sub",Left,Right);
1089 case Instruction::Mul:
1090 case Instruction::FMul:
1091 printBinaryInstruction("mul",Left,Right);
1093 case Instruction::UDiv:
1094 printBinaryInstruction("div.un",Left,Right);
1096 case Instruction::SDiv:
1097 case Instruction::FDiv:
1098 printBinaryInstruction("div",Left,Right);
1100 case Instruction::URem:
1101 printBinaryInstruction("rem.un",Left,Right);
1103 case Instruction::SRem:
1104 case Instruction::FRem:
1105 printBinaryInstruction("rem",Left,Right);
1108 case Instruction::ICmp:
1109 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1111 case Instruction::FCmp:
1112 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1115 case Instruction::And:
1116 printBinaryInstruction("and",Left,Right);
1118 case Instruction::Or:
1119 printBinaryInstruction("or",Left,Right);
1121 case Instruction::Xor:
1122 printBinaryInstruction("xor",Left,Right);
1124 case Instruction::Shl:
1125 printValueLoad(Left);
1126 printValueLoad(Right);
1127 printSimpleInstruction("conv.i4");
1128 printSimpleInstruction("shl");
1130 case Instruction::LShr:
1131 printValueLoad(Left);
1132 printValueLoad(Right);
1133 printSimpleInstruction("conv.i4");
1134 printSimpleInstruction("shr.un");
1136 case Instruction::AShr:
1137 printValueLoad(Left);
1138 printValueLoad(Right);
1139 printSimpleInstruction("conv.i4");
1140 printSimpleInstruction("shr");
1142 case Instruction::Select:
1143 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1145 case Instruction::Load:
1146 printIndirectLoad(Inst->getOperand(0));
1148 case Instruction::Store:
1149 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1151 case Instruction::SExt:
1152 printCastInstruction(Inst->getOpcode(),Left,
1153 cast<CastInst>(Inst)->getDestTy(),
1154 cast<CastInst>(Inst)->getSrcTy());
1156 case Instruction::Trunc:
1157 case Instruction::ZExt:
1158 case Instruction::FPTrunc:
1159 case Instruction::FPExt:
1160 case Instruction::UIToFP:
1161 case Instruction::SIToFP:
1162 case Instruction::FPToUI:
1163 case Instruction::FPToSI:
1164 case Instruction::PtrToInt:
1165 case Instruction::IntToPtr:
1166 case Instruction::BitCast:
1167 printCastInstruction(Inst->getOpcode(),Left,
1168 cast<CastInst>(Inst)->getDestTy());
1170 case Instruction::GetElementPtr:
1171 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1172 gep_type_end(Inst));
1174 case Instruction::Call:
1175 printCallInstruction(cast<CallInst>(Inst));
1177 case Instruction::Invoke:
1178 printInvokeInstruction(cast<InvokeInst>(Inst));
1180 case Instruction::Unwind:
1181 printSimpleInstruction("newobj",
1182 "instance void [mscorlib]System.Exception::.ctor()");
1183 printSimpleInstruction("throw");
1185 case Instruction::Switch:
1186 printSwitchInstruction(cast<SwitchInst>(Inst));
1188 case Instruction::Alloca:
1189 printAllocaInstruction(cast<AllocaInst>(Inst));
1191 case Instruction::Unreachable:
1192 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1193 printSimpleInstruction("newobj",
1194 "instance void [mscorlib]System.Exception::.ctor(string)");
1195 printSimpleInstruction("throw");
1197 case Instruction::VAArg:
1198 printVAArgInstruction(cast<VAArgInst>(Inst));
1201 errs() << "Instruction = " << Inst->getName() << '\n';
1202 llvm_unreachable("Unsupported instruction");
1207 void MSILWriter::printLoop(const Loop* L) {
1208 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1209 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1210 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1211 BasicBlock* BB = blocks[I];
1212 Loop* BBLoop = LInfo->getLoopFor(BB);
1214 printBasicBlock(BB);
1215 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1218 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1222 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1223 Out << getLabelName(BB) << ":\n";
1224 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1225 const Instruction* Inst = I;
1226 // Comment llvm original instruction
1227 // Out << "\n//" << *Inst << "\n";
1228 // Do not handle PHI instruction in current block
1229 if (Inst->getOpcode()==Instruction::PHI) continue;
1230 // Print instruction
1231 printInstruction(Inst);
1233 if (Inst->getType()!=Type::getVoidTy(BB->getContext())) {
1234 // Do not save value after invoke, it done in "try" block
1235 if (Inst->getOpcode()==Instruction::Invoke) continue;
1236 printValueSave(Inst);
1242 void MSILWriter::printLocalVariables(const Function& F) {
1244 const Type* Ty = NULL;
1245 std::set<const Value*> Printed;
1246 const Value* VaList = NULL;
1247 unsigned StackDepth = 8;
1248 // Find local variables
1249 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
1250 if (I->getOpcode()==Instruction::Call ||
1251 I->getOpcode()==Instruction::Invoke) {
1252 // Test stack depth.
1253 if (StackDepth<I->getNumOperands())
1254 StackDepth = I->getNumOperands();
1256 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1257 if (AI && !isa<GlobalVariable>(AI)) {
1258 // Local variable allocation.
1259 Ty = PointerType::getUnqual(AI->getAllocatedType());
1260 Name = getValueName(AI);
1261 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1262 } else if (I->getType()!=Type::getVoidTy(F.getContext())) {
1263 // Operation result.
1265 Name = getValueName(&*I);
1266 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1268 // Test on 'va_list' variable
1269 bool isVaList = false;
1270 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1271 // "va_list" as "va_arg" instruction operand.
1273 VaList = VaInst->getOperand(0);
1274 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1275 // "va_list" as intrinsic function operand.
1276 switch (Inst->getIntrinsicID()) {
1277 case Intrinsic::vastart:
1278 case Intrinsic::vaend:
1279 case Intrinsic::vacopy:
1281 VaList = Inst->getOperand(1);
1287 // Print "va_list" variable.
1288 if (isVaList && Printed.insert(VaList).second) {
1289 Name = getValueName(VaList);
1290 Name.insert(Name.length()-1,"$valist");
1291 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1295 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1299 void MSILWriter::printFunctionBody(const Function& F) {
1301 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1302 if (Loop *L = LInfo->getLoopFor(I)) {
1303 if (L->getHeader()==I && L->getParentLoop()==0)
1312 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1313 const Value *left = 0, *right = 0;
1314 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1315 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1316 // Print instruction
1317 switch (CE->getOpcode()) {
1318 case Instruction::Trunc:
1319 case Instruction::ZExt:
1320 case Instruction::SExt:
1321 case Instruction::FPTrunc:
1322 case Instruction::FPExt:
1323 case Instruction::UIToFP:
1324 case Instruction::SIToFP:
1325 case Instruction::FPToUI:
1326 case Instruction::FPToSI:
1327 case Instruction::PtrToInt:
1328 case Instruction::IntToPtr:
1329 case Instruction::BitCast:
1330 printCastInstruction(CE->getOpcode(),left,CE->getType());
1332 case Instruction::GetElementPtr:
1333 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1335 case Instruction::ICmp:
1336 printICmpInstruction(CE->getPredicate(),left,right);
1338 case Instruction::FCmp:
1339 printFCmpInstruction(CE->getPredicate(),left,right);
1341 case Instruction::Select:
1342 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1344 case Instruction::Add:
1345 case Instruction::FAdd:
1346 printBinaryInstruction("add",left,right);
1348 case Instruction::Sub:
1349 case Instruction::FSub:
1350 printBinaryInstruction("sub",left,right);
1352 case Instruction::Mul:
1353 case Instruction::FMul:
1354 printBinaryInstruction("mul",left,right);
1356 case Instruction::UDiv:
1357 printBinaryInstruction("div.un",left,right);
1359 case Instruction::SDiv:
1360 case Instruction::FDiv:
1361 printBinaryInstruction("div",left,right);
1363 case Instruction::URem:
1364 printBinaryInstruction("rem.un",left,right);
1366 case Instruction::SRem:
1367 case Instruction::FRem:
1368 printBinaryInstruction("rem",left,right);
1370 case Instruction::And:
1371 printBinaryInstruction("and",left,right);
1373 case Instruction::Or:
1374 printBinaryInstruction("or",left,right);
1376 case Instruction::Xor:
1377 printBinaryInstruction("xor",left,right);
1379 case Instruction::Shl:
1380 printBinaryInstruction("shl",left,right);
1382 case Instruction::LShr:
1383 printBinaryInstruction("shr.un",left,right);
1385 case Instruction::AShr:
1386 printBinaryInstruction("shr",left,right);
1389 errs() << "Expression = " << *CE << "\n";
1390 llvm_unreachable("Invalid constant expression");
1395 void MSILWriter::printStaticInitializerList() {
1396 // List of global variables with uninitialized fields.
1397 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1398 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1400 const std::vector<StaticInitializer>& InitList = VarI->second;
1401 if (InitList.empty()) continue;
1402 // For each uninitialized field.
1403 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1404 E = InitList.end(); I!=E; ++I) {
1405 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
1406 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1407 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
1408 // Load variable address
1409 printValueLoad(VarI->first);
1412 printPtrLoad(I->offset);
1413 printSimpleInstruction("add");
1416 printConstantExpr(CE);
1417 // Save result at offset
1418 std::string postfix = getTypePostfix(CE->getType(),true);
1419 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1420 postfix = "stind."+postfix;
1421 printSimpleInstruction(postfix.c_str());
1423 errs() << "Constant = " << *I->constant << '\n';
1424 llvm_unreachable("Invalid static initializer");
1431 void MSILWriter::printFunction(const Function& F) {
1432 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
1433 Out << "\n.method static ";
1434 Out << (F.hasLocalLinkage() ? "private " : "public ");
1435 if (F.isVarArg()) Out << "vararg ";
1436 Out << getTypeName(F.getReturnType(),isSigned) <<
1437 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1440 unsigned ArgIdx = 1;
1441 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1443 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
1444 if (I!=F.arg_begin()) Out << ", ";
1445 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1447 Out << ") cil managed\n";
1450 printLocalVariables(F);
1451 printFunctionBody(F);
1456 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1458 std::set<const Type*> Printed;
1459 for (std::set<const Type*>::const_iterator
1460 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1461 const Type* Ty = *UI;
1462 if (Ty->isArrayTy() || Ty->isVectorTy() || Ty->isStructTy())
1463 Name = getTypeName(Ty, false, true);
1464 // Type with no need to declare.
1466 // Print not duplicated type
1467 if (Printed.insert(Ty).second) {
1468 Out << ".class value explicit ansi sealed '" << Name << "'";
1469 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
1476 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1477 unsigned int N = Ty->getPrimitiveSizeInBits();
1478 assert(N!=0 && "Invalid type in getBitWidth()");
1487 errs() << "Bits = " << N << '\n';
1488 llvm_unreachable("Unsupported integer width");
1490 return 0; // Not reached
1494 void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1495 uint64_t TySize = 0;
1496 const Type* Ty = C->getType();
1497 // Print zero initialized constant.
1498 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
1499 TySize = TD->getTypeAllocSize(C->getType());
1501 Out << "int8 (0) [" << TySize << "]";
1504 // Print constant initializer
1505 switch (Ty->getTypeID()) {
1506 case Type::IntegerTyID: {
1507 TySize = TD->getTypeAllocSize(Ty);
1508 const ConstantInt* Int = cast<ConstantInt>(C);
1509 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1512 case Type::FloatTyID:
1513 case Type::DoubleTyID: {
1514 TySize = TD->getTypeAllocSize(Ty);
1515 const ConstantFP* FP = cast<ConstantFP>(C);
1516 if (Ty->getTypeID() == Type::FloatTyID)
1518 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1521 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1524 case Type::ArrayTyID:
1525 case Type::VectorTyID:
1526 case Type::StructTyID:
1527 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1528 if (I!=0) Out << ",\n";
1529 printStaticConstant(cast<Constant>(C->getOperand(I)), Offset);
1532 case Type::PointerTyID:
1533 TySize = TD->getTypeAllocSize(C->getType());
1534 // Initialize with global variable address
1535 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1536 std::string name = getValueName(G);
1537 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1539 // Dynamic initialization
1540 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1541 InitListPtr->push_back(StaticInitializer(C,Offset));
1542 // Null pointer initialization
1543 if (TySize==4) Out << "int32 (0)";
1544 else if (TySize==8) Out << "int64 (0)";
1545 else llvm_unreachable("Invalid pointer size");
1549 errs() << "TypeID = " << Ty->getTypeID() << '\n';
1550 llvm_unreachable("Invalid type in printStaticConstant()");
1557 void MSILWriter::printStaticInitializer(const Constant* C,
1558 const std::string& Name) {
1559 switch (C->getType()->getTypeID()) {
1560 case Type::IntegerTyID:
1561 case Type::FloatTyID:
1562 case Type::DoubleTyID:
1563 Out << getPrimitiveTypeName(C->getType(), false);
1565 case Type::ArrayTyID:
1566 case Type::VectorTyID:
1567 case Type::StructTyID:
1568 case Type::PointerTyID:
1569 Out << getTypeName(C->getType());
1572 errs() << "Type = " << *C << "\n";
1573 llvm_unreachable("Invalid constant type");
1575 // Print initializer
1576 std::string label = Name;
1577 label.insert(label.length()-1,"$data");
1578 Out << Name << " at " << label << '\n';
1579 Out << ".data " << label << " = {\n";
1580 uint64_t offset = 0;
1581 printStaticConstant(C,offset);
1586 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1587 const Constant* C = G->getInitializer();
1588 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1591 InitListPtr = &StaticInitList[G];
1592 printStaticInitializer(C,getValueName(G));
1596 void MSILWriter::printGlobalVariables() {
1597 if (ModulePtr->global_empty()) return;
1598 Module::global_iterator I,E;
1599 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1600 // Variable definition
1601 Out << ".field static " << (I->isDeclaration() ? "public " :
1603 if (I->isDeclaration()) {
1604 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1606 printVariableDefinition(&*I);
1611 const char* MSILWriter::getLibraryName(const Function* F) {
1612 return getLibraryForSymbol(F->getName(), true, F->getCallingConv());
1616 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1617 return getLibraryForSymbol(GV->getName(), false, CallingConv::C);
1621 const char* MSILWriter::getLibraryForSymbol(const StringRef &Name,
1623 CallingConv::ID CallingConv) {
1624 // TODO: Read *.def file with function and libraries definitions.
1625 return "MSVCRT.DLL";
1629 void MSILWriter::printExternals() {
1630 Module::const_iterator I,E;
1632 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1634 if (I->isIntrinsic()) continue;
1635 if (I->isDeclaration()) {
1636 const Function* F = I;
1637 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1639 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1640 Out << ".method static hidebysig pinvokeimpl(\""
1641 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1644 // External variables and static initialization.
1646 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1647 " native int LoadLibrary(string) preservesig {}\n"
1648 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1649 " native int GetProcAddress(native int, string) preservesig {}\n";
1651 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1654 "\tcall\tnative int LoadLibrary(string)\n"
1656 "\tcall\tnative int GetProcAddress(native int,string)\n"
1659 "\tldstr\t\"Can no import variable\"\n"
1660 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1665 ".method static private void $MSIL_Init() managed cil\n{\n";
1666 printStaticInitializerList();
1667 // Foreach global variable.
1668 for (Module::global_iterator I = ModulePtr->global_begin(),
1669 E = ModulePtr->global_end(); I!=E; ++I) {
1670 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1671 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1672 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1673 printSimpleInstruction("ldsflda",Tmp.c_str());
1674 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1675 Out << "\tldstr\t\"" << I->getName() << "\"\n";
1676 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1677 printIndirectSave(I->getType());
1679 printSimpleInstruction("ret");
1684 //===----------------------------------------------------------------------===//
1685 // External Interface declaration
1686 //===----------------------------------------------------------------------===//
1688 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1689 formatted_raw_ostream &o,
1690 CodeGenFileType FileType,
1691 CodeGenOpt::Level OptLevel)
1693 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
1694 MSILWriter* Writer = new MSILWriter(o);
1695 PM.add(createGCLoweringPass());
1696 // FIXME: Handle switch through native IL instruction "switch"
1697 PM.add(createLowerSwitchPass());
1698 PM.add(createCFGSimplificationPass());
1699 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1701 PM.add(createGCInfoDeleter());