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/Transforms/Scalar.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/CodeGen/Passes.h"
30 // TargetMachine for the MSIL
31 struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
32 const TargetData DataLayout; // Calculates type size & alignment
34 MSILTarget(const Target &T, const Module &M, const std::string &FS)
35 : TargetMachine(T), DataLayout(&M) {}
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 // This class always works, but shouldn't be the default in most cases.
44 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
46 virtual const TargetData *getTargetData() const { return &DataLayout; }
50 /// MSILTargetMachineModule - Note that this is used on hosts that
51 /// cannot link in a library unless there are references into the
52 /// library. In particular, it seems that it is not possible to get
53 /// things to work on Win32 without this. Though it is unused, do not
55 extern "C" int MSILTargetMachineModule;
56 int MSILTargetMachineModule = 0;
58 extern Target TheMSILTarget;
59 static RegisterTarget<MSILTarget> X(TheMSILTarget, "msil", "MSIL backend");
61 // Force static initialization.
62 extern "C" void LLVMInitializeMSILTarget() { }
64 bool MSILModule::runOnModule(Module &M) {
66 TD = &getAnalysis<TargetData>();
69 TypeSymbolTable& Table = M.getTypeSymbolTable();
70 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
71 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
72 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
75 std::set<const Type *>::iterator T = Types.find(I->second);
84 // Find unnamed types.
85 unsigned RenameCounter = 0;
86 for (std::set<const Type *>::const_iterator I = Types.begin(),
87 E = Types.end(); I!=E; ++I)
88 if (const StructType *STy = dyn_cast<StructType>(*I)) {
89 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
93 // Pointer for FunctionPass.
94 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
98 char MSILModule::ID = 0;
99 char MSILWriter::ID = 0;
101 bool MSILWriter::runOnFunction(Function &F) {
102 if (F.isDeclaration()) return false;
104 // Do not codegen any 'available_externally' functions at all, they have
105 // definitions outside the translation unit.
106 if (F.hasAvailableExternallyLinkage())
109 LInfo = &getAnalysis<LoopInfo>();
115 bool MSILWriter::doInitialization(Module &M) {
117 Mang = new Mangler(M);
118 Out << ".assembly extern mscorlib {}\n";
119 Out << ".assembly MSIL {}\n\n";
120 Out << "// External\n";
122 Out << "// Declarations\n";
123 printDeclarations(M.getTypeSymbolTable());
124 Out << "// Definitions\n";
125 printGlobalVariables();
126 Out << "// Startup code\n";
127 printModuleStartup();
132 bool MSILWriter::doFinalization(Module &M) {
138 void MSILWriter::printModuleStartup() {
140 ".method static public int32 $MSIL_Startup() {\n"
142 "\t.locals (native int i)\n"
143 "\t.locals (native int argc)\n"
144 "\t.locals (native int ptr)\n"
145 "\t.locals (void* argv)\n"
146 "\t.locals (string[] args)\n"
147 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
154 printPtrLoad(TD->getPointerSize());
169 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
170 "StringToHGlobalAnsi(string)\n"
174 printPtrLoad(TD->getPointerSize());
186 "\tcall void $MSIL_Init()\n";
188 // Call user 'main' function.
189 const Function* F = ModulePtr->getFunction("main");
190 if (!F || F->isDeclaration()) {
191 Out << "\tldc.i4.0\n\tret\n}\n";
195 std::string Args("");
196 Function::const_arg_iterator Arg1,Arg2;
198 switch (F->arg_size()) {
203 Arg1 = F->arg_begin();
204 if (Arg1->getType()->isInteger()) {
205 Out << "\tldloc\targc\n";
206 Args = getTypeName(Arg1->getType());
211 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
212 if (Arg1->getType()->isInteger() &&
213 Arg2->getType()->getTypeID() == Type::PointerTyID) {
214 Out << "\tldloc\targc\n\tldloc\targv\n";
215 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
223 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
224 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
225 Out << "\tldc.i4.0\n";
227 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
228 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
230 Out << "\tldc.i4.0\n";
232 Out << "\tconv.i4\n";
237 bool MSILWriter::isZeroValue(const Value* V) {
238 if (const Constant *C = dyn_cast<Constant>(V))
239 return C->isNullValue();
244 std::string MSILWriter::getValueName(const Value* V) {
246 if (const GlobalValue *GV = cast<GlobalValue>(V))
247 Name = Mang->getMangledName(GV);
249 unsigned &No = AnonValueNumbers[V];
250 if (No == 0) No = ++NextAnonValueNumber;
251 Name = "tmp" + utostr(No);
254 // Name into the quotes allow control and space characters.
259 std::string MSILWriter::getLabelName(const std::string& Name) {
260 if (Name.find('.')!=std::string::npos) {
261 std::string Tmp(Name);
262 // Replace unaccepable characters in the label name.
263 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
264 if (*I=='.') *I = '@';
271 std::string MSILWriter::getLabelName(const Value* V) {
273 if (const GlobalValue *GV = cast<GlobalValue>(V))
274 Name = Mang->getMangledName(GV);
276 unsigned &No = AnonValueNumbers[V];
277 if (No == 0) No = ++NextAnonValueNumber;
278 Name = "tmp" + utostr(No);
281 return getLabelName(Name);
285 std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
286 switch (CallingConvID) {
288 case CallingConv::Cold:
289 case CallingConv::Fast:
290 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
291 case CallingConv::X86_FastCall:
292 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
293 case CallingConv::X86_StdCall:
294 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
296 cerr << "CallingConvID = " << CallingConvID << '\n';
297 llvm_unreachable("Unsupported calling convention");
299 return ""; // Not reached
303 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
304 std::string Tmp = "";
305 const Type* ElemTy = Ty;
306 assert(Ty->getTypeID()==TyID && "Invalid type passed");
307 // Walk trought array element types.
309 // Multidimensional array.
310 if (ElemTy->getTypeID()==TyID) {
311 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
312 Tmp += utostr(ATy->getNumElements());
313 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
314 Tmp += utostr(VTy->getNumElements());
315 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
317 // Base element type found.
318 if (ElemTy->getTypeID()!=TyID) break;
321 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
325 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
326 unsigned NumBits = 0;
327 switch (Ty->getTypeID()) {
330 case Type::IntegerTyID:
331 NumBits = getBitWidth(Ty);
335 return "unsigned int"+utostr(NumBits)+" ";
336 return "int"+utostr(NumBits)+" ";
337 case Type::FloatTyID:
339 case Type::DoubleTyID:
342 cerr << "Type = " << *Ty << '\n';
343 llvm_unreachable("Invalid primitive type");
345 return ""; // Not reached
349 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
351 if (Ty->isPrimitiveType() || Ty->isInteger())
352 return getPrimitiveTypeName(Ty,isSigned);
353 // FIXME: "OpaqueType" support
354 switch (Ty->getTypeID()) {
355 case Type::PointerTyID:
357 case Type::StructTyID:
359 return ModulePtr->getTypeName(Ty);
360 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
361 case Type::ArrayTyID:
363 return getArrayTypeName(Ty->getTypeID(),Ty);
364 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
365 case Type::VectorTyID:
367 return getArrayTypeName(Ty->getTypeID(),Ty);
368 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
370 cerr << "Type = " << *Ty << '\n';
371 llvm_unreachable("Invalid type in getTypeName()");
373 return ""; // Not reached
377 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
379 if (isa<Argument>(V))
382 else if (const Function* F = dyn_cast<Function>(V))
383 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
385 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
386 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
388 else if (isa<Constant>(V))
389 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
395 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
397 unsigned NumBits = 0;
398 switch (Ty->getTypeID()) {
399 // Integer constant, expanding for stack operations.
400 case Type::IntegerTyID:
401 NumBits = getBitWidth(Ty);
402 // Expand integer value to "int32" or "int64".
403 if (Expand) return (NumBits<=32 ? "i4" : "i8");
404 if (NumBits==1) return "i1";
405 return (isSigned ? "i" : "u")+utostr(NumBits/8);
407 case Type::FloatTyID:
409 case Type::DoubleTyID:
411 case Type::PointerTyID:
412 return "i"+utostr(TD->getTypeAllocSize(Ty));
414 cerr << "TypeID = " << Ty->getTypeID() << '\n';
415 llvm_unreachable("Invalid type in TypeToPostfix()");
417 return ""; // Not reached
421 void MSILWriter::printConvToPtr() {
422 switch (ModulePtr->getPointerSize()) {
423 case Module::Pointer32:
424 printSimpleInstruction("conv.u4");
426 case Module::Pointer64:
427 printSimpleInstruction("conv.u8");
430 llvm_unreachable("Module use not supporting pointer size");
435 void MSILWriter::printPtrLoad(uint64_t N) {
436 switch (ModulePtr->getPointerSize()) {
437 case Module::Pointer32:
438 printSimpleInstruction("ldc.i4",utostr(N).c_str());
439 // FIXME: Need overflow test?
441 cerr << "Value = " << utostr(N) << '\n';
442 llvm_unreachable("32-bit pointer overflowed");
445 case Module::Pointer64:
446 printSimpleInstruction("ldc.i8",utostr(N).c_str());
449 llvm_unreachable("Module use not supporting pointer size");
454 void MSILWriter::printValuePtrLoad(const Value* V) {
460 void MSILWriter::printConstLoad(const Constant* C) {
461 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
463 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
464 if (CInt->isMinValue(true))
465 Out << CInt->getSExtValue();
467 Out << CInt->getZExtValue();
468 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
472 if (FP->getType()->getTypeID()==Type::FloatTyID) {
473 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
476 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
479 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
480 } else if (isa<UndefValue>(C)) {
481 // Undefined constant value = NULL.
484 cerr << "Constant = " << *C << '\n';
485 llvm_unreachable("Invalid constant value");
491 void MSILWriter::printValueLoad(const Value* V) {
492 MSILWriter::ValueType Location = getValueLocation(V);
494 // Global variable or function address.
497 if (const Function* F = dyn_cast<Function>(V)) {
498 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
499 printSimpleInstruction("ldftn",
500 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
503 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
504 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
505 Tmp = "void* "+getValueName(V);
506 printSimpleInstruction("ldsfld",Tmp.c_str());
508 Tmp = getTypeName(ElemTy)+getValueName(V);
509 printSimpleInstruction("ldsflda",Tmp.c_str());
513 // Function argument.
515 printSimpleInstruction("ldarg",getValueName(V).c_str());
517 // Local function variable.
519 printSimpleInstruction("ldloc",getValueName(V).c_str());
523 if (isa<ConstantPointerNull>(V))
526 printConstLoad(cast<Constant>(V));
528 // Constant expression.
530 printConstantExpr(cast<ConstantExpr>(V));
533 cerr << "Value = " << *V << '\n';
534 llvm_unreachable("Invalid value location");
539 void MSILWriter::printValueSave(const Value* V) {
540 switch (getValueLocation(V)) {
542 printSimpleInstruction("starg",getValueName(V).c_str());
545 printSimpleInstruction("stloc",getValueName(V).c_str());
548 cerr << "Value = " << *V << '\n';
549 llvm_unreachable("Invalid value location");
554 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
555 const Value* Right) {
556 printValueLoad(Left);
557 printValueLoad(Right);
558 Out << '\t' << Name << '\n';
562 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
564 Out << '\t' << Inst << '\t' << Operand << '\n';
566 Out << '\t' << Inst << '\n';
570 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
571 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
572 isa<PHINode>(I); ++I) {
573 const PHINode* Phi = cast<PHINode>(I);
574 const Value* Val = Phi->getIncomingValueForBlock(Src);
575 if (isa<UndefValue>(Val)) continue;
582 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
583 const BasicBlock* TrueBB,
584 const BasicBlock* FalseBB) {
585 if (TrueBB==FalseBB) {
586 // "TrueBB" and "FalseBB" destination equals
587 printPHICopy(CurrBB,TrueBB);
588 printSimpleInstruction("pop");
589 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
590 } else if (FalseBB==NULL) {
591 // If "FalseBB" not used the jump have condition
592 printPHICopy(CurrBB,TrueBB);
593 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
594 } else if (TrueBB==NULL) {
595 // If "TrueBB" not used the jump is unconditional
596 printPHICopy(CurrBB,FalseBB);
597 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
599 // Copy PHI instructions for each block
600 std::string TmpLabel;
601 // Print PHI instructions for "TrueBB"
602 if (isa<PHINode>(TrueBB->begin())) {
603 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
604 printSimpleInstruction("brtrue",TmpLabel.c_str());
606 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
608 // Print PHI instructions for "FalseBB"
609 if (isa<PHINode>(FalseBB->begin())) {
610 printPHICopy(CurrBB,FalseBB);
611 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
613 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
615 if (isa<PHINode>(TrueBB->begin())) {
616 // Handle "TrueBB" PHI Copy
617 Out << TmpLabel << ":\n";
618 printPHICopy(CurrBB,TrueBB);
619 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
625 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
626 if (Inst->isUnconditional()) {
627 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
629 printValueLoad(Inst->getCondition());
630 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
631 Inst->getSuccessor(1));
636 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
637 const Value* VFalse) {
638 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
639 printValueLoad(VTrue);
640 printValueLoad(Cond);
641 printSimpleInstruction("brtrue",TmpLabel.c_str());
642 printSimpleInstruction("pop");
643 printValueLoad(VFalse);
644 Out << TmpLabel << ":\n";
648 void MSILWriter::printIndirectLoad(const Value* V) {
649 const Type* Ty = V->getType();
651 if (const PointerType* P = dyn_cast<PointerType>(Ty))
652 Ty = P->getElementType();
653 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
654 printSimpleInstruction(Tmp.c_str());
658 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
661 printIndirectSave(Val->getType());
665 void MSILWriter::printIndirectSave(const Type* Ty) {
666 // Instruction need signed postfix for any type.
667 std::string postfix = getTypePostfix(Ty, false);
668 if (*postfix.begin()=='u') *postfix.begin() = 'i';
669 postfix = "stind."+postfix;
670 printSimpleInstruction(postfix.c_str());
674 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
675 const Type* Ty, const Type* SrcTy) {
680 case Instruction::SExt:
681 // If sign extending int, convert first from unsigned to signed
682 // with the same bit size - because otherwise we will loose the sign.
684 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
685 printSimpleInstruction(Tmp.c_str());
688 case Instruction::SIToFP:
689 case Instruction::FPToSI:
690 Tmp = "conv."+getTypePostfix(Ty,false,true);
691 printSimpleInstruction(Tmp.c_str());
694 case Instruction::FPTrunc:
695 case Instruction::FPExt:
696 case Instruction::UIToFP:
697 case Instruction::Trunc:
698 case Instruction::ZExt:
699 case Instruction::FPToUI:
700 case Instruction::PtrToInt:
701 case Instruction::IntToPtr:
702 Tmp = "conv."+getTypePostfix(Ty,false);
703 printSimpleInstruction(Tmp.c_str());
706 case Instruction::BitCast:
707 // FIXME: meaning that ld*/st* instruction do not change data format.
710 cerr << "Opcode = " << Op << '\n';
711 llvm_unreachable("Invalid conversion instruction");
716 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
717 gep_type_iterator E) {
720 printValuePtrLoad(V);
721 // Calculate element offset.
724 const Value* IndexValue = I.getOperand();
725 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
726 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
727 // Offset is the sum of all previous structure fields.
728 for (uint64_t F = 0; F<FieldIndex; ++F)
729 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
731 printSimpleInstruction("add");
733 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
734 Size = TD->getTypeAllocSize(SeqTy->getElementType());
736 Size = TD->getTypeAllocSize(*I);
738 // Add offset of current element to stack top.
739 if (!isZeroValue(IndexValue)) {
740 // Constant optimization.
741 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
742 if (C->getValue().isNegative()) {
743 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
744 printSimpleInstruction("sub");
747 printPtrLoad(C->getZExtValue()*Size);
750 printValuePtrLoad(IndexValue);
751 printSimpleInstruction("mul");
753 printSimpleInstruction("add");
759 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
760 const Instruction* Inst,
763 if (Ty->isVarArg()) Tmp += "vararg ";
764 // Name and return type.
765 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
766 // Function argument type list.
767 unsigned NumParams = Ty->getNumParams();
768 for (unsigned I = 0; I!=NumParams; ++I) {
769 if (I!=0) Tmp += ",";
770 Tmp += getTypeName(Ty->getParamType(I));
772 // CLR needs to know the exact amount of parameters received by vararg
773 // function, because caller cleans the stack.
774 if (Ty->isVarArg() && Inst) {
775 // Origin to function arguments in "CallInst" or "InvokeInst".
776 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
777 // Print variable argument types.
778 unsigned NumOperands = Inst->getNumOperands()-Org;
779 if (NumParams<NumOperands) {
780 if (NumParams!=0) Tmp += ", ";
782 for (unsigned J = NumParams; J!=NumOperands; ++J) {
783 if (J!=NumParams) Tmp += ", ";
784 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
792 void MSILWriter::printFunctionCall(const Value* FnVal,
793 const Instruction* Inst) {
794 // Get function calling convention.
795 std::string Name = "";
796 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
797 Name = getConvModopt(Call->getCallingConv());
798 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
799 Name = getConvModopt(Invoke->getCallingConv());
801 cerr << "Instruction = " << Inst->getName() << '\n';
802 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
804 if (const Function* F = dyn_cast<Function>(FnVal)) {
806 Name += getValueName(F);
807 printSimpleInstruction("call",
808 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
810 // Indirect function call.
811 const PointerType* PTy = cast<PointerType>(FnVal->getType());
812 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
813 // Load function address.
814 printValueLoad(FnVal);
815 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
820 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
822 switch (Inst->getIntrinsicID()) {
823 case Intrinsic::vastart:
824 Name = getValueName(Inst->getOperand(1));
825 Name.insert(Name.length()-1,"$valist");
826 // Obtain the argument handle.
827 printSimpleInstruction("ldloca",Name.c_str());
828 printSimpleInstruction("arglist");
829 printSimpleInstruction("call",
830 "instance void [mscorlib]System.ArgIterator::.ctor"
831 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
832 // Save as pointer type "void*"
833 printValueLoad(Inst->getOperand(1));
834 printSimpleInstruction("ldloca",Name.c_str());
835 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
837 case Intrinsic::vaend:
838 // Close argument list handle.
839 printIndirectLoad(Inst->getOperand(1));
840 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
842 case Intrinsic::vacopy:
843 // Copy "ArgIterator" valuetype.
844 printIndirectLoad(Inst->getOperand(1));
845 printIndirectLoad(Inst->getOperand(2));
846 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
849 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
850 llvm_unreachable("Invalid intrinsic function");
855 void MSILWriter::printCallInstruction(const Instruction* Inst) {
856 if (isa<IntrinsicInst>(Inst)) {
857 // Handle intrinsic function.
858 printIntrinsicCall(cast<IntrinsicInst>(Inst));
860 // Load arguments to stack and call function.
861 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
862 printValueLoad(Inst->getOperand(I));
863 printFunctionCall(Inst->getOperand(0),Inst);
868 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
869 const Value* Right) {
871 case ICmpInst::ICMP_EQ:
872 printBinaryInstruction("ceq",Left,Right);
874 case ICmpInst::ICMP_NE:
875 // Emulate = not neg (Op1 eq Op2)
876 printBinaryInstruction("ceq",Left,Right);
877 printSimpleInstruction("neg");
878 printSimpleInstruction("not");
880 case ICmpInst::ICMP_ULE:
881 case ICmpInst::ICMP_SLE:
882 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
883 printBinaryInstruction("ceq",Left,Right);
884 if (Predicate==ICmpInst::ICMP_ULE)
885 printBinaryInstruction("clt.un",Left,Right);
887 printBinaryInstruction("clt",Left,Right);
888 printSimpleInstruction("or");
890 case ICmpInst::ICMP_UGE:
891 case ICmpInst::ICMP_SGE:
892 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
893 printBinaryInstruction("ceq",Left,Right);
894 if (Predicate==ICmpInst::ICMP_UGE)
895 printBinaryInstruction("cgt.un",Left,Right);
897 printBinaryInstruction("cgt",Left,Right);
898 printSimpleInstruction("or");
900 case ICmpInst::ICMP_ULT:
901 printBinaryInstruction("clt.un",Left,Right);
903 case ICmpInst::ICMP_SLT:
904 printBinaryInstruction("clt",Left,Right);
906 case ICmpInst::ICMP_UGT:
907 printBinaryInstruction("cgt.un",Left,Right);
909 case ICmpInst::ICMP_SGT:
910 printBinaryInstruction("cgt",Left,Right);
913 cerr << "Predicate = " << Predicate << '\n';
914 llvm_unreachable("Invalid icmp predicate");
919 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
920 const Value* Right) {
921 // FIXME: Correct comparison
922 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
924 case FCmpInst::FCMP_UGT:
925 // X > Y || llvm_fcmp_uno(X, Y)
926 printBinaryInstruction("cgt",Left,Right);
927 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
928 printSimpleInstruction("or");
930 case FCmpInst::FCMP_OGT:
932 printBinaryInstruction("cgt",Left,Right);
934 case FCmpInst::FCMP_UGE:
935 // X >= Y || llvm_fcmp_uno(X, Y)
936 printBinaryInstruction("ceq",Left,Right);
937 printBinaryInstruction("cgt",Left,Right);
938 printSimpleInstruction("or");
939 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
940 printSimpleInstruction("or");
942 case FCmpInst::FCMP_OGE:
944 printBinaryInstruction("ceq",Left,Right);
945 printBinaryInstruction("cgt",Left,Right);
946 printSimpleInstruction("or");
948 case FCmpInst::FCMP_ULT:
949 // X < Y || llvm_fcmp_uno(X, Y)
950 printBinaryInstruction("clt",Left,Right);
951 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
952 printSimpleInstruction("or");
954 case FCmpInst::FCMP_OLT:
956 printBinaryInstruction("clt",Left,Right);
958 case FCmpInst::FCMP_ULE:
959 // X <= Y || llvm_fcmp_uno(X, Y)
960 printBinaryInstruction("ceq",Left,Right);
961 printBinaryInstruction("clt",Left,Right);
962 printSimpleInstruction("or");
963 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
964 printSimpleInstruction("or");
966 case FCmpInst::FCMP_OLE:
968 printBinaryInstruction("ceq",Left,Right);
969 printBinaryInstruction("clt",Left,Right);
970 printSimpleInstruction("or");
972 case FCmpInst::FCMP_UEQ:
973 // X == Y || llvm_fcmp_uno(X, Y)
974 printBinaryInstruction("ceq",Left,Right);
975 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
976 printSimpleInstruction("or");
978 case FCmpInst::FCMP_OEQ:
980 printBinaryInstruction("ceq",Left,Right);
982 case FCmpInst::FCMP_UNE:
984 printBinaryInstruction("ceq",Left,Right);
985 printSimpleInstruction("neg");
986 printSimpleInstruction("not");
988 case FCmpInst::FCMP_ONE:
989 // X != Y && llvm_fcmp_ord(X, Y)
990 printBinaryInstruction("ceq",Left,Right);
991 printSimpleInstruction("not");
993 case FCmpInst::FCMP_ORD:
994 // return X == X && Y == Y
995 printBinaryInstruction("ceq",Left,Left);
996 printBinaryInstruction("ceq",Right,Right);
997 printSimpleInstruction("or");
999 case FCmpInst::FCMP_UNO:
1001 printBinaryInstruction("ceq",Left,Left);
1002 printSimpleInstruction("not");
1003 printBinaryInstruction("ceq",Right,Right);
1004 printSimpleInstruction("not");
1005 printSimpleInstruction("or");
1008 llvm_unreachable("Illegal FCmp predicate");
1013 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1014 std::string Label = "leave$normal_"+utostr(getUniqID());
1017 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1018 printValueLoad(Inst->getOperand(I));
1019 // Print call instruction
1020 printFunctionCall(Inst->getOperand(0),Inst);
1021 // Save function result and leave "try" block
1022 printValueSave(Inst);
1023 printSimpleInstruction("leave",Label.c_str());
1025 Out << "catch [mscorlib]System.Exception {\n";
1026 // Redirect to unwind block
1027 printSimpleInstruction("pop");
1028 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1029 Out << "}\n" << Label << ":\n";
1030 // Redirect to continue block
1031 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1035 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1036 // FIXME: Emulate with IL "switch" instruction
1037 // Emulate = if () else if () else if () else ...
1038 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1039 printValueLoad(Inst->getCondition());
1040 printValueLoad(Inst->getCaseValue(I));
1041 printSimpleInstruction("ceq");
1042 // Condition jump to successor block
1043 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1045 // Jump to default block
1046 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1050 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1051 printIndirectLoad(Inst->getOperand(0));
1052 printSimpleInstruction("call",
1053 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1054 printSimpleInstruction("refanyval","void*");
1056 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
1057 printSimpleInstruction(Name.c_str());
1061 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
1062 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
1063 // Constant optimization.
1064 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1065 printPtrLoad(CInt->getZExtValue()*Size);
1068 printValueLoad(Inst->getOperand(0));
1069 printSimpleInstruction("mul");
1071 printSimpleInstruction("localloc");
1075 void MSILWriter::printInstruction(const Instruction* Inst) {
1076 const Value *Left = 0, *Right = 0;
1077 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1078 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1079 // Print instruction
1080 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
1081 switch (Inst->getOpcode()) {
1083 case Instruction::Ret:
1084 if (Inst->getNumOperands()) {
1085 printValueLoad(Left);
1086 printSimpleInstruction("ret");
1088 printSimpleInstruction("ret");
1090 case Instruction::Br:
1091 printBranchInstruction(cast<BranchInst>(Inst));
1094 case Instruction::Add:
1095 case Instruction::FAdd:
1096 printBinaryInstruction("add",Left,Right);
1098 case Instruction::Sub:
1099 case Instruction::FSub:
1100 printBinaryInstruction("sub",Left,Right);
1102 case Instruction::Mul:
1103 case Instruction::FMul:
1104 printBinaryInstruction("mul",Left,Right);
1106 case Instruction::UDiv:
1107 printBinaryInstruction("div.un",Left,Right);
1109 case Instruction::SDiv:
1110 case Instruction::FDiv:
1111 printBinaryInstruction("div",Left,Right);
1113 case Instruction::URem:
1114 printBinaryInstruction("rem.un",Left,Right);
1116 case Instruction::SRem:
1117 case Instruction::FRem:
1118 printBinaryInstruction("rem",Left,Right);
1121 case Instruction::ICmp:
1122 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1124 case Instruction::FCmp:
1125 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1128 case Instruction::And:
1129 printBinaryInstruction("and",Left,Right);
1131 case Instruction::Or:
1132 printBinaryInstruction("or",Left,Right);
1134 case Instruction::Xor:
1135 printBinaryInstruction("xor",Left,Right);
1137 case Instruction::Shl:
1138 printValueLoad(Left);
1139 printValueLoad(Right);
1140 printSimpleInstruction("conv.i4");
1141 printSimpleInstruction("shl");
1143 case Instruction::LShr:
1144 printValueLoad(Left);
1145 printValueLoad(Right);
1146 printSimpleInstruction("conv.i4");
1147 printSimpleInstruction("shr.un");
1149 case Instruction::AShr:
1150 printValueLoad(Left);
1151 printValueLoad(Right);
1152 printSimpleInstruction("conv.i4");
1153 printSimpleInstruction("shr");
1155 case Instruction::Select:
1156 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1158 case Instruction::Load:
1159 printIndirectLoad(Inst->getOperand(0));
1161 case Instruction::Store:
1162 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1164 case Instruction::SExt:
1165 printCastInstruction(Inst->getOpcode(),Left,
1166 cast<CastInst>(Inst)->getDestTy(),
1167 cast<CastInst>(Inst)->getSrcTy());
1169 case Instruction::Trunc:
1170 case Instruction::ZExt:
1171 case Instruction::FPTrunc:
1172 case Instruction::FPExt:
1173 case Instruction::UIToFP:
1174 case Instruction::SIToFP:
1175 case Instruction::FPToUI:
1176 case Instruction::FPToSI:
1177 case Instruction::PtrToInt:
1178 case Instruction::IntToPtr:
1179 case Instruction::BitCast:
1180 printCastInstruction(Inst->getOpcode(),Left,
1181 cast<CastInst>(Inst)->getDestTy());
1183 case Instruction::GetElementPtr:
1184 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1185 gep_type_end(Inst));
1187 case Instruction::Call:
1188 printCallInstruction(cast<CallInst>(Inst));
1190 case Instruction::Invoke:
1191 printInvokeInstruction(cast<InvokeInst>(Inst));
1193 case Instruction::Unwind:
1194 printSimpleInstruction("newobj",
1195 "instance void [mscorlib]System.Exception::.ctor()");
1196 printSimpleInstruction("throw");
1198 case Instruction::Switch:
1199 printSwitchInstruction(cast<SwitchInst>(Inst));
1201 case Instruction::Alloca:
1202 printAllocaInstruction(cast<AllocaInst>(Inst));
1204 case Instruction::Malloc:
1205 llvm_unreachable("LowerAllocationsPass used");
1207 case Instruction::Free:
1208 llvm_unreachable("LowerAllocationsPass used");
1210 case Instruction::Unreachable:
1211 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1212 printSimpleInstruction("newobj",
1213 "instance void [mscorlib]System.Exception::.ctor(string)");
1214 printSimpleInstruction("throw");
1216 case Instruction::VAArg:
1217 printVAArgInstruction(cast<VAArgInst>(Inst));
1220 cerr << "Instruction = " << Inst->getName() << '\n';
1221 llvm_unreachable("Unsupported instruction");
1226 void MSILWriter::printLoop(const Loop* L) {
1227 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1228 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1229 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1230 BasicBlock* BB = blocks[I];
1231 Loop* BBLoop = LInfo->getLoopFor(BB);
1233 printBasicBlock(BB);
1234 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1237 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1241 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1242 Out << getLabelName(BB) << ":\n";
1243 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1244 const Instruction* Inst = I;
1245 // Comment llvm original instruction
1246 // Out << "\n//" << *Inst << "\n";
1247 // Do not handle PHI instruction in current block
1248 if (Inst->getOpcode()==Instruction::PHI) continue;
1249 // Print instruction
1250 printInstruction(Inst);
1252 if (Inst->getType()!=Type::VoidTy) {
1253 // Do not save value after invoke, it done in "try" block
1254 if (Inst->getOpcode()==Instruction::Invoke) continue;
1255 printValueSave(Inst);
1261 void MSILWriter::printLocalVariables(const Function& F) {
1263 const Type* Ty = NULL;
1264 std::set<const Value*> Printed;
1265 const Value* VaList = NULL;
1266 unsigned StackDepth = 8;
1267 // Find local variables
1268 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
1269 if (I->getOpcode()==Instruction::Call ||
1270 I->getOpcode()==Instruction::Invoke) {
1271 // Test stack depth.
1272 if (StackDepth<I->getNumOperands())
1273 StackDepth = I->getNumOperands();
1275 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1276 if (AI && !isa<GlobalVariable>(AI)) {
1277 // Local variable allocation.
1278 Ty = PointerType::getUnqual(AI->getAllocatedType());
1279 Name = getValueName(AI);
1280 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1281 } else if (I->getType()!=Type::VoidTy) {
1282 // Operation result.
1284 Name = getValueName(&*I);
1285 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1287 // Test on 'va_list' variable
1288 bool isVaList = false;
1289 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1290 // "va_list" as "va_arg" instruction operand.
1292 VaList = VaInst->getOperand(0);
1293 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1294 // "va_list" as intrinsic function operand.
1295 switch (Inst->getIntrinsicID()) {
1296 case Intrinsic::vastart:
1297 case Intrinsic::vaend:
1298 case Intrinsic::vacopy:
1300 VaList = Inst->getOperand(1);
1306 // Print "va_list" variable.
1307 if (isVaList && Printed.insert(VaList).second) {
1308 Name = getValueName(VaList);
1309 Name.insert(Name.length()-1,"$valist");
1310 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1314 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1318 void MSILWriter::printFunctionBody(const Function& F) {
1320 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1321 if (Loop *L = LInfo->getLoopFor(I)) {
1322 if (L->getHeader()==I && L->getParentLoop()==0)
1331 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1332 const Value *left = 0, *right = 0;
1333 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1334 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1335 // Print instruction
1336 switch (CE->getOpcode()) {
1337 case Instruction::Trunc:
1338 case Instruction::ZExt:
1339 case Instruction::SExt:
1340 case Instruction::FPTrunc:
1341 case Instruction::FPExt:
1342 case Instruction::UIToFP:
1343 case Instruction::SIToFP:
1344 case Instruction::FPToUI:
1345 case Instruction::FPToSI:
1346 case Instruction::PtrToInt:
1347 case Instruction::IntToPtr:
1348 case Instruction::BitCast:
1349 printCastInstruction(CE->getOpcode(),left,CE->getType());
1351 case Instruction::GetElementPtr:
1352 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1354 case Instruction::ICmp:
1355 printICmpInstruction(CE->getPredicate(),left,right);
1357 case Instruction::FCmp:
1358 printFCmpInstruction(CE->getPredicate(),left,right);
1360 case Instruction::Select:
1361 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1363 case Instruction::Add:
1364 case Instruction::FAdd:
1365 printBinaryInstruction("add",left,right);
1367 case Instruction::Sub:
1368 case Instruction::FSub:
1369 printBinaryInstruction("sub",left,right);
1371 case Instruction::Mul:
1372 case Instruction::FMul:
1373 printBinaryInstruction("mul",left,right);
1375 case Instruction::UDiv:
1376 printBinaryInstruction("div.un",left,right);
1378 case Instruction::SDiv:
1379 case Instruction::FDiv:
1380 printBinaryInstruction("div",left,right);
1382 case Instruction::URem:
1383 printBinaryInstruction("rem.un",left,right);
1385 case Instruction::SRem:
1386 case Instruction::FRem:
1387 printBinaryInstruction("rem",left,right);
1389 case Instruction::And:
1390 printBinaryInstruction("and",left,right);
1392 case Instruction::Or:
1393 printBinaryInstruction("or",left,right);
1395 case Instruction::Xor:
1396 printBinaryInstruction("xor",left,right);
1398 case Instruction::Shl:
1399 printBinaryInstruction("shl",left,right);
1401 case Instruction::LShr:
1402 printBinaryInstruction("shr.un",left,right);
1404 case Instruction::AShr:
1405 printBinaryInstruction("shr",left,right);
1408 cerr << "Expression = " << *CE << "\n";
1409 llvm_unreachable("Invalid constant expression");
1414 void MSILWriter::printStaticInitializerList() {
1415 // List of global variables with uninitialized fields.
1416 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1417 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1419 const std::vector<StaticInitializer>& InitList = VarI->second;
1420 if (InitList.empty()) continue;
1421 // For each uninitialized field.
1422 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1423 E = InitList.end(); I!=E; ++I) {
1424 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
1425 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1426 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
1427 // Load variable address
1428 printValueLoad(VarI->first);
1431 printPtrLoad(I->offset);
1432 printSimpleInstruction("add");
1435 printConstantExpr(CE);
1436 // Save result at offset
1437 std::string postfix = getTypePostfix(CE->getType(),true);
1438 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1439 postfix = "stind."+postfix;
1440 printSimpleInstruction(postfix.c_str());
1442 cerr << "Constant = " << *I->constant << '\n';
1443 llvm_unreachable("Invalid static initializer");
1450 void MSILWriter::printFunction(const Function& F) {
1451 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
1452 Out << "\n.method static ";
1453 Out << (F.hasLocalLinkage() ? "private " : "public ");
1454 if (F.isVarArg()) Out << "vararg ";
1455 Out << getTypeName(F.getReturnType(),isSigned) <<
1456 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1459 unsigned ArgIdx = 1;
1460 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1462 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
1463 if (I!=F.arg_begin()) Out << ", ";
1464 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1466 Out << ") cil managed\n";
1469 printLocalVariables(F);
1470 printFunctionBody(F);
1475 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1477 std::set<const Type*> Printed;
1478 for (std::set<const Type*>::const_iterator
1479 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1480 const Type* Ty = *UI;
1481 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1482 Name = getTypeName(Ty, false, true);
1483 // Type with no need to declare.
1485 // Print not duplicated type
1486 if (Printed.insert(Ty).second) {
1487 Out << ".class value explicit ansi sealed '" << Name << "'";
1488 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
1495 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1496 unsigned int N = Ty->getPrimitiveSizeInBits();
1497 assert(N!=0 && "Invalid type in getBitWidth()");
1506 cerr << "Bits = " << N << '\n';
1507 llvm_unreachable("Unsupported integer width");
1509 return 0; // Not reached
1513 void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1514 uint64_t TySize = 0;
1515 const Type* Ty = C->getType();
1516 // Print zero initialized constant.
1517 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
1518 TySize = TD->getTypeAllocSize(C->getType());
1520 Out << "int8 (0) [" << TySize << "]";
1523 // Print constant initializer
1524 switch (Ty->getTypeID()) {
1525 case Type::IntegerTyID: {
1526 TySize = TD->getTypeAllocSize(Ty);
1527 const ConstantInt* Int = cast<ConstantInt>(C);
1528 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1531 case Type::FloatTyID:
1532 case Type::DoubleTyID: {
1533 TySize = TD->getTypeAllocSize(Ty);
1534 const ConstantFP* FP = cast<ConstantFP>(C);
1535 if (Ty->getTypeID() == Type::FloatTyID)
1537 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1540 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1543 case Type::ArrayTyID:
1544 case Type::VectorTyID:
1545 case Type::StructTyID:
1546 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1547 if (I!=0) Out << ",\n";
1548 printStaticConstant(C->getOperand(I),Offset);
1551 case Type::PointerTyID:
1552 TySize = TD->getTypeAllocSize(C->getType());
1553 // Initialize with global variable address
1554 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1555 std::string name = getValueName(G);
1556 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1558 // Dynamic initialization
1559 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1560 InitListPtr->push_back(StaticInitializer(C,Offset));
1561 // Null pointer initialization
1562 if (TySize==4) Out << "int32 (0)";
1563 else if (TySize==8) Out << "int64 (0)";
1564 else llvm_unreachable("Invalid pointer size");
1568 cerr << "TypeID = " << Ty->getTypeID() << '\n';
1569 llvm_unreachable("Invalid type in printStaticConstant()");
1576 void MSILWriter::printStaticInitializer(const Constant* C,
1577 const std::string& Name) {
1578 switch (C->getType()->getTypeID()) {
1579 case Type::IntegerTyID:
1580 case Type::FloatTyID:
1581 case Type::DoubleTyID:
1582 Out << getPrimitiveTypeName(C->getType(), false);
1584 case Type::ArrayTyID:
1585 case Type::VectorTyID:
1586 case Type::StructTyID:
1587 case Type::PointerTyID:
1588 Out << getTypeName(C->getType());
1591 cerr << "Type = " << *C << "\n";
1592 llvm_unreachable("Invalid constant type");
1594 // Print initializer
1595 std::string label = Name;
1596 label.insert(label.length()-1,"$data");
1597 Out << Name << " at " << label << '\n';
1598 Out << ".data " << label << " = {\n";
1599 uint64_t offset = 0;
1600 printStaticConstant(C,offset);
1605 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1606 const Constant* C = G->getInitializer();
1607 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1610 InitListPtr = &StaticInitList[G];
1611 printStaticInitializer(C,getValueName(G));
1615 void MSILWriter::printGlobalVariables() {
1616 if (ModulePtr->global_empty()) return;
1617 Module::global_iterator I,E;
1618 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1619 // Variable definition
1620 Out << ".field static " << (I->isDeclaration() ? "public " :
1622 if (I->isDeclaration()) {
1623 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1625 printVariableDefinition(&*I);
1630 const char* MSILWriter::getLibraryName(const Function* F) {
1631 return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1635 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1636 return getLibraryForSymbol(Mang->getMangledName(GV).c_str(), false, 0);
1640 const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1641 unsigned CallingConv) {
1642 // TODO: Read *.def file with function and libraries definitions.
1643 return "MSVCRT.DLL";
1647 void MSILWriter::printExternals() {
1648 Module::const_iterator I,E;
1650 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1652 if (I->isIntrinsic()) continue;
1653 if (I->isDeclaration()) {
1654 const Function* F = I;
1655 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1657 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1658 Out << ".method static hidebysig pinvokeimpl(\""
1659 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1662 // External variables and static initialization.
1664 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1665 " native int LoadLibrary(string) preservesig {}\n"
1666 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1667 " native int GetProcAddress(native int, string) preservesig {}\n";
1669 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1672 "\tcall\tnative int LoadLibrary(string)\n"
1674 "\tcall\tnative int GetProcAddress(native int,string)\n"
1677 "\tldstr\t\"Can no import variable\"\n"
1678 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1683 ".method static private void $MSIL_Init() managed cil\n{\n";
1684 printStaticInitializerList();
1685 // Foreach global variable.
1686 for (Module::global_iterator I = ModulePtr->global_begin(),
1687 E = ModulePtr->global_end(); I!=E; ++I) {
1688 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1689 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1690 std::string Label = "not_null$_"+utostr(getUniqID());
1691 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1692 printSimpleInstruction("ldsflda",Tmp.c_str());
1693 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1694 Out << "\tldstr\t\"" << Mang->getMangledName(&*I) << "\"\n";
1695 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1696 printIndirectSave(I->getType());
1698 printSimpleInstruction("ret");
1703 //===----------------------------------------------------------------------===//
1704 // External Interface declaration
1705 //===----------------------------------------------------------------------===//
1707 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1708 formatted_raw_ostream &o,
1709 CodeGenFileType FileType,
1710 CodeGenOpt::Level OptLevel)
1712 if (FileType != TargetMachine::AssemblyFile) return true;
1713 MSILWriter* Writer = new MSILWriter(o);
1714 PM.add(createGCLoweringPass());
1715 PM.add(createLowerAllocationsPass(true));
1716 // FIXME: Handle switch trougth native IL instruction "switch"
1717 PM.add(createLowerSwitchPass());
1718 PM.add(createCFGSimplificationPass());
1719 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1721 PM.add(createGCInfoDeleter());