Uniformize the names of type predicates: rather than having isFloatTy and
[oota-llvm.git] / lib / Target / MSIL / MSILWriter.cpp
1 //===-- MSILWriter.cpp - Library for converting LLVM code to MSIL ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library converts LLVM code to MSIL code.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
29 using namespace llvm;
30
31 namespace llvm {
32   // TargetMachine for the MSIL 
33   struct MSILTarget : public TargetMachine {
34     MSILTarget(const Target &T, const std::string &TT, const std::string &FS)
35       : TargetMachine(T) {}
36
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);
42
43     virtual const TargetData *getTargetData() const { return 0; }
44   };
45 }
46
47 extern "C" void LLVMInitializeMSILTarget() {
48   // Register the target.
49   RegisterTargetMachine<MSILTarget> X(TheMSILTarget);
50 }
51
52 bool MSILModule::runOnModule(Module &M) {
53   ModulePtr = &M;
54   TD = &getAnalysis<TargetData>();
55   bool Changed = false;
56   // Find named types.  
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 (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
61       Table.remove(I++);
62     else {
63       std::set<const Type *>::iterator T = Types.find(I->second);
64       if (T==Types.end())
65         Table.remove(I++);
66       else {
67         Types.erase(T);
68         ++I;
69       }
70     }
71   }
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))
78         ++RenameCounter;
79       Changed = true;
80     }
81   // Pointer for FunctionPass.
82   UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
83   return Changed;
84 }
85
86 char MSILModule::ID = 0;
87 char MSILWriter::ID = 0;
88
89 bool MSILWriter::runOnFunction(Function &F) {
90   if (F.isDeclaration()) return false;
91
92   // Do not codegen any 'available_externally' functions at all, they have
93   // definitions outside the translation unit.
94   if (F.hasAvailableExternallyLinkage())
95     return false;
96
97   LInfo = &getAnalysis<LoopInfo>();
98   printFunction(F);
99   return false;
100 }
101
102
103 bool MSILWriter::doInitialization(Module &M) {
104   ModulePtr = &M;
105   Out << ".assembly extern mscorlib {}\n";
106   Out << ".assembly MSIL {}\n\n";
107   Out << "// External\n";
108   printExternals();
109   Out << "// Declarations\n";
110   printDeclarations(M.getTypeSymbolTable());
111   Out << "// Definitions\n";
112   printGlobalVariables();
113   Out << "// Startup code\n";
114   printModuleStartup();
115   return false;
116 }
117
118
119 bool MSILWriter::doFinalization(Module &M) {
120   return false;
121 }
122
123
124 void MSILWriter::printModuleStartup() {
125   Out <<
126   ".method static public int32 $MSIL_Startup() {\n"
127   "\t.entrypoint\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"
134   "\tdup\n"
135   "\tstloc\targs\n"
136   "\tldlen\n"
137   "\tconv.i4\n"
138   "\tdup\n"
139   "\tstloc\targc\n";
140   printPtrLoad(TD->getPointerSize());
141   Out <<
142   "\tmul\n"
143   "\tlocalloc\n"
144   "\tstloc\targv\n"
145   "\tldc.i4.0\n"
146   "\tstloc\ti\n"
147   "L_01:\n"
148   "\tldloc\ti\n"
149   "\tldloc\targc\n"
150   "\tceq\n"
151   "\tbrtrue\tL_02\n"
152   "\tldloc\targs\n"
153   "\tldloc\ti\n"
154   "\tldelem.ref\n"
155   "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
156            "StringToHGlobalAnsi(string)\n"
157   "\tstloc\tptr\n"
158   "\tldloc\targv\n"
159   "\tldloc\ti\n";
160   printPtrLoad(TD->getPointerSize());
161   Out << 
162   "\tmul\n"
163   "\tadd\n"
164   "\tldloc\tptr\n"
165   "\tstind.i\n"
166   "\tldloc\ti\n"
167   "\tldc.i4.1\n"
168   "\tadd\n"
169   "\tstloc\ti\n"
170   "\tbr\tL_01\n"
171   "L_02:\n"
172   "\tcall void $MSIL_Init()\n";
173
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";
178     return;
179   }
180   bool BadSig = true;
181   std::string Args("");
182   Function::const_arg_iterator Arg1,Arg2;
183
184   switch (F->arg_size()) {
185   case 0:
186     BadSig = false;
187     break;
188   case 1:
189     Arg1 = F->arg_begin();
190     if (Arg1->getType()->isIntegerTy()) {
191       Out << "\tldloc\targc\n";
192       Args = getTypeName(Arg1->getType());
193       BadSig = false;
194     }
195     break;
196   case 2:
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());
202       BadSig = false;
203     }
204     break;
205   default:
206     BadSig = true;
207   }
208
209   bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
210   if (BadSig || (!F->getReturnType()->isIntegerTy() && !RetVoid)) {
211     Out << "\tldc.i4.0\n";
212   } else {
213     Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
214       getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
215     if (RetVoid)
216       Out << "\tldc.i4.0\n";
217     else
218       Out << "\tconv.i4\n";
219   }
220   Out << "\tret\n}\n";
221 }
222
223 bool MSILWriter::isZeroValue(const Value* V) {
224   if (const Constant *C = dyn_cast<Constant>(V))
225     return C->isNullValue();
226   return false;
227 }
228
229
230 std::string MSILWriter::getValueName(const Value* V) {
231   std::string Name;
232   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
233     Name = GV->getName();
234   else {
235     unsigned &No = AnonValueNumbers[V];
236     if (No == 0) No = ++NextAnonValueNumber;
237     Name = "tmp" + utostr(No);
238   }
239   
240   // Name into the quotes allow control and space characters.
241   return "'"+Name+"'";
242 }
243
244
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 = '@';
251     return Tmp;
252   }
253   return Name;
254 }
255
256
257 std::string MSILWriter::getLabelName(const Value* V) {
258   std::string Name;
259   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
260     Name = GV->getName();
261   else {
262     unsigned &No = AnonValueNumbers[V];
263     if (No == 0) No = ++NextAnonValueNumber;
264     Name = "tmp" + utostr(No);
265   }
266   
267   return getLabelName(Name);
268 }
269
270
271 std::string MSILWriter::getConvModopt(CallingConv::ID CallingConvID) {
272   switch (CallingConvID) {
273   case CallingConv::C:
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) ";
281   default:
282     errs() << "CallingConvID = " << CallingConvID << '\n';
283     llvm_unreachable("Unsupported calling convention");
284   }
285   return ""; // Not reached
286 }
287
288
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.
294   for (;;) {
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();
302     }
303     // Base element type found.
304     if (ElemTy->getTypeID()!=TyID) break;
305     Tmp += ",";
306   }
307   return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
308 }
309
310
311 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
312   unsigned NumBits = 0;
313   switch (Ty->getTypeID()) {
314   case Type::VoidTyID:
315     return "void ";
316   case Type::IntegerTyID:
317     NumBits = getBitWidth(Ty);
318     if(NumBits==1)
319       return "bool ";
320     if (!isSigned)
321       return "unsigned int"+utostr(NumBits)+" ";
322     return "int"+utostr(NumBits)+" ";
323   case Type::FloatTyID:
324     return "float32 ";
325   case Type::DoubleTyID:
326     return "float64 "; 
327   default:
328     errs() << "Type = " << *Ty << '\n';
329     llvm_unreachable("Invalid primitive type");
330   }
331   return ""; // Not reached
332 }
333
334
335 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
336                                     bool isNested) {
337   if (Ty->isPrimitiveType() || Ty->isIntegerTy())
338     return getPrimitiveTypeName(Ty,isSigned);
339   // FIXME: "OpaqueType" support
340   switch (Ty->getTypeID()) {
341   case Type::PointerTyID:
342     return "void* ";
343   case Type::StructTyID:
344     if (isNested)
345       return ModulePtr->getTypeName(Ty);
346     return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
347   case Type::ArrayTyID:
348     if (isNested)
349       return getArrayTypeName(Ty->getTypeID(),Ty);
350     return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
351   case Type::VectorTyID:
352     if (isNested)
353       return getArrayTypeName(Ty->getTypeID(),Ty);
354     return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
355   default:
356     errs() << "Type = " << *Ty << '\n';
357     llvm_unreachable("Invalid type in getTypeName()");
358   }
359   return ""; // Not reached
360 }
361
362
363 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
364   // Function argument
365   if (isa<Argument>(V))
366     return ArgumentVT;
367   // Function
368   else if (const Function* F = dyn_cast<Function>(V))
369     return F->hasLocalLinkage() ? InternalVT : GlobalVT;
370   // Variable
371   else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
372     return G->hasLocalLinkage() ? InternalVT : GlobalVT;
373   // Constant
374   else if (isa<Constant>(V))
375     return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
376   // Local variable
377   return LocalVT;
378 }
379
380
381 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
382                                        bool isSigned) {
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);
392   // Float constant.
393   case Type::FloatTyID:
394     return "r4";
395   case Type::DoubleTyID:
396     return "r8";
397   case Type::PointerTyID:
398     return "i"+utostr(TD->getTypeAllocSize(Ty));
399   default:
400     errs() << "TypeID = " << Ty->getTypeID() << '\n';
401     llvm_unreachable("Invalid type in TypeToPostfix()");
402   }
403   return ""; // Not reached
404 }
405
406
407 void MSILWriter::printConvToPtr() {
408   switch (ModulePtr->getPointerSize()) {
409   case Module::Pointer32:
410     printSimpleInstruction("conv.u4");
411     break;
412   case Module::Pointer64:
413     printSimpleInstruction("conv.u8");
414     break;
415   default:
416     llvm_unreachable("Module use not supporting pointer size");
417   }
418 }
419
420
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?
426     if (!isUInt32(N)) {
427       errs() << "Value = " << utostr(N) << '\n';
428       llvm_unreachable("32-bit pointer overflowed");
429     }
430     break;
431   case Module::Pointer64:
432     printSimpleInstruction("ldc.i8",utostr(N).c_str());
433     break;
434   default:
435     llvm_unreachable("Module use not supporting pointer size");
436   }
437 }
438
439
440 void MSILWriter::printValuePtrLoad(const Value* V) {
441   printValueLoad(V);
442   printConvToPtr();
443 }
444
445
446 void MSILWriter::printConstLoad(const Constant* C) {
447   if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
448     // Integer constant
449     Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
450     if (CInt->isMinValue(true))
451       Out << CInt->getSExtValue();
452     else
453       Out << CInt->getZExtValue();
454   } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
455     // Float constant
456     uint64_t X;
457     unsigned Size;
458     if (FP->getType()->getTypeID()==Type::FloatTyID) {
459       X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
460       Size = 4;  
461     } else {
462       X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
463       Size = 8;  
464     }
465     Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
466   } else if (isa<UndefValue>(C)) {
467     // Undefined constant value = NULL.
468     printPtrLoad(0);
469   } else {
470     errs() << "Constant = " << *C << '\n';
471     llvm_unreachable("Invalid constant value");
472   }
473   Out << '\n';
474 }
475
476
477 void MSILWriter::printValueLoad(const Value* V) {
478   MSILWriter::ValueType Location = getValueLocation(V);
479   switch (Location) {
480   // Global variable or function address.
481   case GlobalVT:
482   case InternalVT:
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());
487     } else {
488       std::string Tmp;
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());
493       } else {
494         Tmp = getTypeName(ElemTy)+getValueName(V);
495         printSimpleInstruction("ldsflda",Tmp.c_str());
496       }
497     }
498     break;
499   // Function argument.
500   case ArgumentVT:
501     printSimpleInstruction("ldarg",getValueName(V).c_str());
502     break;
503   // Local function variable.
504   case LocalVT:
505     printSimpleInstruction("ldloc",getValueName(V).c_str());
506     break;
507   // Constant value.
508   case ConstVT:
509     if (isa<ConstantPointerNull>(V))
510       printPtrLoad(0);
511     else
512       printConstLoad(cast<Constant>(V));
513     break;
514   // Constant expression.
515   case ConstExprVT:
516     printConstantExpr(cast<ConstantExpr>(V));
517     break;
518   default:
519     errs() << "Value = " << *V << '\n';
520     llvm_unreachable("Invalid value location");
521   }
522 }
523
524
525 void MSILWriter::printValueSave(const Value* V) {
526   switch (getValueLocation(V)) {
527   case ArgumentVT:
528     printSimpleInstruction("starg",getValueName(V).c_str());
529     break;
530   case LocalVT:
531     printSimpleInstruction("stloc",getValueName(V).c_str());
532     break;
533   default:
534     errs() << "Value  = " << *V << '\n';
535     llvm_unreachable("Invalid value location");
536   }
537 }
538
539
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';
545 }
546
547
548 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
549   if(Operand) 
550     Out << '\t' << Inst << '\t' << Operand << '\n';
551   else
552     Out << '\t' << Inst << '\n';
553 }
554
555
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;
561     printValueLoad(Val);
562     printValueSave(Phi);
563   }
564 }
565
566
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());
583   } else {
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());
590     } else {
591       printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
592     }
593     // Print PHI instructions for "FalseBB"
594     if (isa<PHINode>(FalseBB->begin())) {
595       printPHICopy(CurrBB,FalseBB);
596       printSimpleInstruction("br",getLabelName(FalseBB).c_str());
597     } else {
598       printSimpleInstruction("br",getLabelName(FalseBB).c_str());
599     }
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());
605     }
606   }
607 }
608
609
610 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
611   if (Inst->isUnconditional()) {
612     printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
613   } else {
614     printValueLoad(Inst->getCondition());
615     printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
616                        Inst->getSuccessor(1));
617   }
618 }
619
620
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";
630 }
631
632
633 void MSILWriter::printIndirectLoad(const Value* V) {
634   const Type* Ty = V->getType();
635   printValueLoad(V);
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());
640 }
641
642
643 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
644   printValueLoad(Ptr);
645   printValueLoad(Val);
646   printIndirectSave(Val->getType());
647 }
648
649
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());
656 }
657
658
659 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
660                                       const Type* Ty, const Type* SrcTy) {
661   std::string Tmp("");
662   printValueLoad(V);
663   switch (Op) {
664   // Signed
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.
668     if (SrcTy) {
669       Tmp = "conv."+getTypePostfix(SrcTy,false,true);
670       printSimpleInstruction(Tmp.c_str());
671     }
672     // FALLTHROUGH
673   case Instruction::SIToFP:
674   case Instruction::FPToSI:
675     Tmp = "conv."+getTypePostfix(Ty,false,true);
676     printSimpleInstruction(Tmp.c_str());
677     break;
678   // Unsigned
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());
689     break;
690   // Do nothing
691   case Instruction::BitCast:
692     // FIXME: meaning that ld*/st* instruction do not change data format.
693     break;
694   default:
695     errs() << "Opcode = " << Op << '\n';
696     llvm_unreachable("Invalid conversion instruction");
697   }
698 }
699
700
701 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
702                                      gep_type_iterator E) {
703   unsigned Size;
704   // Load address
705   printValuePtrLoad(V);
706   // Calculate element offset.
707   for (; I!=E; ++I){
708     Size = 0;
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));
715       printPtrLoad(Size);
716       printSimpleInstruction("add");
717       continue;
718     } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
719       Size = TD->getTypeAllocSize(SeqTy->getElementType());
720     } else {
721       Size = TD->getTypeAllocSize(*I);
722     }
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");
730           continue;
731         } else
732           printPtrLoad(C->getZExtValue()*Size);
733       } else {
734         printPtrLoad(Size);
735         printValuePtrLoad(IndexValue);
736         printSimpleInstruction("mul");
737       }
738       printSimpleInstruction("add");
739     }
740   }
741 }
742
743
744 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
745                                          const Instruction* Inst,
746                                          std::string Name) {
747   std::string Tmp("");
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));
756   }
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 += ", ";
766       Tmp += "... , ";
767       for (unsigned J = NumParams; J!=NumOperands; ++J) {
768         if (J!=NumParams) Tmp += ", ";
769         Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
770       }
771     }
772   }
773   return Tmp+")";
774 }
775
776
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());
785   else {
786     errs() << "Instruction = " << Inst->getName() << '\n';
787     llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
788   }
789   if (const Function* F = dyn_cast<Function>(FnVal)) {
790     // Direct call.
791     Name += getValueName(F);
792     printSimpleInstruction("call",
793       getCallSignature(F->getFunctionType(),Inst,Name).c_str());
794   } else {
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());
801   }
802 }
803
804
805 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
806   std::string Name;
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)));
822     break;
823   case Intrinsic::vaend:
824     // Close argument list handle.
825     printIndirectLoad(Inst->getOperand(1));
826     printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
827     break;
828   case Intrinsic::vacopy:
829     // Copy "ArgIterator" valuetype.
830     printIndirectLoad(Inst->getOperand(1));
831     printIndirectLoad(Inst->getOperand(2));
832     printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
833     break;        
834   default:
835     errs() << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
836     llvm_unreachable("Invalid intrinsic function");
837   }
838 }
839
840
841 void MSILWriter::printCallInstruction(const Instruction* Inst) {
842   if (isa<IntrinsicInst>(Inst)) {
843     // Handle intrinsic function.
844     printIntrinsicCall(cast<IntrinsicInst>(Inst));
845   } else {
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);
850   }
851 }
852
853
854 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
855                                       const Value* Right) {
856   switch (Predicate) {
857   case ICmpInst::ICMP_EQ:
858     printBinaryInstruction("ceq",Left,Right);
859     break;
860   case ICmpInst::ICMP_NE:
861     // Emulate = not neg (Op1 eq Op2)
862     printBinaryInstruction("ceq",Left,Right);
863     printSimpleInstruction("neg");
864     printSimpleInstruction("not");
865     break;
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);
872     else
873       printBinaryInstruction("clt",Left,Right);
874     printSimpleInstruction("or");
875     break;
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);
882     else
883       printBinaryInstruction("cgt",Left,Right);
884     printSimpleInstruction("or");
885     break;
886   case ICmpInst::ICMP_ULT:
887     printBinaryInstruction("clt.un",Left,Right);
888     break;
889   case ICmpInst::ICMP_SLT:
890     printBinaryInstruction("clt",Left,Right);
891     break;
892   case ICmpInst::ICMP_UGT:
893     printBinaryInstruction("cgt.un",Left,Right);
894     break;
895   case ICmpInst::ICMP_SGT:
896     printBinaryInstruction("cgt",Left,Right);
897     break;
898   default:
899     errs() << "Predicate = " << Predicate << '\n';
900     llvm_unreachable("Invalid icmp predicate");
901   }
902 }
903
904
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)";
909   switch (Predicate) {
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");
915     break;
916   case FCmpInst::FCMP_OGT:
917     // X >  Y
918     printBinaryInstruction("cgt",Left,Right);
919     break;
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");
927     break;
928   case FCmpInst::FCMP_OGE:
929     // X >= Y
930     printBinaryInstruction("ceq",Left,Right);
931     printBinaryInstruction("cgt",Left,Right);
932     printSimpleInstruction("or");
933     break;
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");
939     break;
940   case FCmpInst::FCMP_OLT:
941     // X <  Y
942     printBinaryInstruction("clt",Left,Right);
943     break;
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");
951     break;
952   case FCmpInst::FCMP_OLE:
953     // X <= Y
954     printBinaryInstruction("ceq",Left,Right);
955     printBinaryInstruction("clt",Left,Right);
956     printSimpleInstruction("or");
957     break;
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");
963     break;
964   case FCmpInst::FCMP_OEQ:
965     // X == Y
966     printBinaryInstruction("ceq",Left,Right);
967     break;
968   case FCmpInst::FCMP_UNE:
969     // X != Y
970     printBinaryInstruction("ceq",Left,Right);
971     printSimpleInstruction("neg");
972     printSimpleInstruction("not");
973     break;
974   case FCmpInst::FCMP_ONE:
975     // X != Y && llvm_fcmp_ord(X, Y)
976     printBinaryInstruction("ceq",Left,Right);
977     printSimpleInstruction("not");
978     break;
979   case FCmpInst::FCMP_ORD:
980     // return X == X && Y == Y
981     printBinaryInstruction("ceq",Left,Left);
982     printBinaryInstruction("ceq",Right,Right);
983     printSimpleInstruction("or");
984     break;
985   case FCmpInst::FCMP_UNO:
986     // X != X || Y != Y
987     printBinaryInstruction("ceq",Left,Left);
988     printSimpleInstruction("not");
989     printBinaryInstruction("ceq",Right,Right);
990     printSimpleInstruction("not");
991     printSimpleInstruction("or");
992     break;
993   default:
994     llvm_unreachable("Illegal FCmp predicate");
995   }
996 }
997
998
999 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1000   std::string Label = "leave$normal_"+utostr(getUniqID());
1001   Out << ".try {\n";
1002   // Load arguments
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());
1010   Out << "}\n";
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());
1018 }
1019
1020
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);
1030   }
1031   // Jump to default block
1032   printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1033 }
1034
1035
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*");
1041   std::string Name = 
1042     "ldind."+getTypePostfix(PointerType::getUnqual(
1043             IntegerType::get(Inst->getContext(), 8)),false);
1044   printSimpleInstruction(Name.c_str());
1045 }
1046
1047
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);
1053   } else {
1054     printPtrLoad(Size);
1055     printValueLoad(Inst->getOperand(0));
1056     printSimpleInstruction("mul");
1057   }
1058   printSimpleInstruction("localloc");
1059 }
1060
1061
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()) {
1069   // Terminator
1070   case Instruction::Ret:
1071     if (Inst->getNumOperands()) {
1072       printValueLoad(Left);
1073       printSimpleInstruction("ret");
1074     } else
1075       printSimpleInstruction("ret");
1076     break;
1077   case Instruction::Br:
1078     printBranchInstruction(cast<BranchInst>(Inst));
1079     break;
1080   // Binary
1081   case Instruction::Add:
1082   case Instruction::FAdd:
1083     printBinaryInstruction("add",Left,Right);
1084     break;
1085   case Instruction::Sub:
1086   case Instruction::FSub:
1087     printBinaryInstruction("sub",Left,Right);
1088     break;
1089   case Instruction::Mul:
1090   case Instruction::FMul:
1091     printBinaryInstruction("mul",Left,Right);
1092     break;
1093   case Instruction::UDiv:
1094     printBinaryInstruction("div.un",Left,Right);
1095     break;
1096   case Instruction::SDiv:
1097   case Instruction::FDiv:
1098     printBinaryInstruction("div",Left,Right);
1099     break;
1100   case Instruction::URem:
1101     printBinaryInstruction("rem.un",Left,Right);
1102     break;
1103   case Instruction::SRem:
1104   case Instruction::FRem:
1105     printBinaryInstruction("rem",Left,Right);
1106     break;
1107   // Binary Condition
1108   case Instruction::ICmp:
1109     printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1110     break;
1111   case Instruction::FCmp:
1112     printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1113     break;
1114   // Bitwise Binary
1115   case Instruction::And:
1116     printBinaryInstruction("and",Left,Right);
1117     break;
1118   case Instruction::Or:
1119     printBinaryInstruction("or",Left,Right);
1120     break;
1121   case Instruction::Xor:
1122     printBinaryInstruction("xor",Left,Right);
1123     break;
1124   case Instruction::Shl:
1125     printValueLoad(Left);
1126     printValueLoad(Right);
1127     printSimpleInstruction("conv.i4");
1128     printSimpleInstruction("shl");
1129     break;
1130   case Instruction::LShr:
1131     printValueLoad(Left);
1132     printValueLoad(Right);
1133     printSimpleInstruction("conv.i4");
1134     printSimpleInstruction("shr.un");
1135     break;
1136   case Instruction::AShr:
1137     printValueLoad(Left);
1138     printValueLoad(Right);
1139     printSimpleInstruction("conv.i4");
1140     printSimpleInstruction("shr");
1141     break;
1142   case Instruction::Select:
1143     printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1144     break;
1145   case Instruction::Load:
1146     printIndirectLoad(Inst->getOperand(0));
1147     break;
1148   case Instruction::Store:
1149     printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1150     break;
1151   case Instruction::SExt:
1152     printCastInstruction(Inst->getOpcode(),Left,
1153                          cast<CastInst>(Inst)->getDestTy(),
1154                          cast<CastInst>(Inst)->getSrcTy());
1155     break;
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());
1169     break;
1170   case Instruction::GetElementPtr:
1171     printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1172                         gep_type_end(Inst));
1173     break;
1174   case Instruction::Call:
1175     printCallInstruction(cast<CallInst>(Inst));
1176     break;
1177   case Instruction::Invoke:
1178     printInvokeInstruction(cast<InvokeInst>(Inst));
1179     break;
1180   case Instruction::Unwind:
1181     printSimpleInstruction("newobj",
1182       "instance void [mscorlib]System.Exception::.ctor()");
1183     printSimpleInstruction("throw");
1184     break;
1185   case Instruction::Switch:
1186     printSwitchInstruction(cast<SwitchInst>(Inst));
1187     break;
1188   case Instruction::Alloca:
1189     printAllocaInstruction(cast<AllocaInst>(Inst));
1190     break;
1191   case Instruction::Unreachable:
1192     printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1193     printSimpleInstruction("newobj",
1194       "instance void [mscorlib]System.Exception::.ctor(string)");
1195     printSimpleInstruction("throw");
1196     break;
1197   case Instruction::VAArg:
1198     printVAArgInstruction(cast<VAArgInst>(Inst));
1199     break;
1200   default:
1201     errs() << "Instruction = " << Inst->getName() << '\n';
1202     llvm_unreachable("Unsupported instruction");
1203   }
1204 }
1205
1206
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);
1213     if (BBLoop == L)
1214       printBasicBlock(BB);
1215     else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1216       printLoop(BBLoop);
1217   }
1218   printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1219 }
1220
1221
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);
1232     // Save result
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);
1237     }
1238   }
1239 }
1240
1241
1242 void MSILWriter::printLocalVariables(const Function& F) {
1243   std::string Name;
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();
1255     }
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.
1264       Ty = I->getType();
1265       Name = getValueName(&*I);
1266       Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1267     }
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.
1272       isVaList = true;
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:
1280         isVaList = true;
1281         VaList = Inst->getOperand(1);
1282         break;
1283       default:
1284         isVaList = false;
1285       }
1286     }
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 "
1292           << Name << ")\n";
1293     }
1294   }
1295   printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1296 }
1297
1298
1299 void MSILWriter::printFunctionBody(const Function& F) {
1300   // Print body
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)
1304         printLoop(L);
1305     } else {
1306       printBasicBlock(I);
1307     }
1308   }
1309 }
1310
1311
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());
1331     break;
1332   case Instruction::GetElementPtr:
1333     printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1334     break;
1335   case Instruction::ICmp:
1336     printICmpInstruction(CE->getPredicate(),left,right);
1337     break;
1338   case Instruction::FCmp:
1339     printFCmpInstruction(CE->getPredicate(),left,right);
1340     break;
1341   case Instruction::Select:
1342     printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1343     break;
1344   case Instruction::Add:
1345   case Instruction::FAdd:
1346     printBinaryInstruction("add",left,right);
1347     break;
1348   case Instruction::Sub:
1349   case Instruction::FSub:
1350     printBinaryInstruction("sub",left,right);
1351     break;
1352   case Instruction::Mul:
1353   case Instruction::FMul:
1354     printBinaryInstruction("mul",left,right);
1355     break;
1356   case Instruction::UDiv:
1357     printBinaryInstruction("div.un",left,right);
1358     break;
1359   case Instruction::SDiv:
1360   case Instruction::FDiv:
1361     printBinaryInstruction("div",left,right);
1362     break;
1363   case Instruction::URem:
1364     printBinaryInstruction("rem.un",left,right);
1365     break;
1366   case Instruction::SRem:
1367   case Instruction::FRem:
1368     printBinaryInstruction("rem",left,right);
1369     break;
1370   case Instruction::And:
1371     printBinaryInstruction("and",left,right);
1372     break;
1373   case Instruction::Or:
1374     printBinaryInstruction("or",left,right);
1375     break;
1376   case Instruction::Xor:
1377     printBinaryInstruction("xor",left,right);
1378     break;
1379   case Instruction::Shl:
1380     printBinaryInstruction("shl",left,right);
1381     break;
1382   case Instruction::LShr:
1383     printBinaryInstruction("shr.un",left,right);
1384     break;
1385   case Instruction::AShr:
1386     printBinaryInstruction("shr",left,right);
1387     break;
1388   default:
1389     errs() << "Expression = " << *CE << "\n";
1390     llvm_unreachable("Invalid constant expression");
1391   }
1392 }
1393
1394
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;
1399        ++VarI) {
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);
1410         // Add offset
1411         if (I->offset!=0) {
1412           printPtrLoad(I->offset);
1413           printSimpleInstruction("add");
1414         }
1415         // Load value
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());
1422       } else {
1423         errs() << "Constant = " << *I->constant << '\n';
1424         llvm_unreachable("Invalid static initializer");
1425       }
1426     }
1427   }
1428 }
1429
1430
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';
1438   // Arguments
1439   Out << "\t(";
1440   unsigned ArgIdx = 1;
1441   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1442        ++I, ++ArgIdx) {
1443     isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
1444     if (I!=F.arg_begin()) Out << ", ";
1445     Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1446   }
1447   Out << ") cil managed\n";
1448   // Body
1449   Out << "{\n";
1450   printLocalVariables(F);
1451   printFunctionBody(F);
1452   Out << "}\n";
1453 }
1454
1455
1456 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1457   std::string Name;
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 (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1463       Name = getTypeName(Ty, false, true);
1464     // Type with no need to declare.
1465     else continue;
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);
1470       Out << " }\n\n";
1471     }
1472   }
1473 }
1474
1475
1476 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1477   unsigned int N = Ty->getPrimitiveSizeInBits();
1478   assert(N!=0 && "Invalid type in getBitWidth()");
1479   switch (N) {
1480   case 1:
1481   case 8:
1482   case 16:
1483   case 32:
1484   case 64:
1485     return N;
1486   default:
1487     errs() << "Bits = " << N << '\n';
1488     llvm_unreachable("Unsupported integer width");
1489   }
1490   return 0; // Not reached
1491 }
1492
1493
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());
1500     Offset += TySize;
1501     Out << "int8 (0) [" << TySize << "]";
1502     return;
1503   }
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() << ")";
1510     break;
1511   }
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)
1517       Out << "int32 (" << 
1518         (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1519     else
1520       Out << "int64 (" << 
1521         FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1522     break;
1523   }
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);
1530     }
1531     break;
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") << ")";
1538     } else {
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");
1546     }
1547     break;
1548   default:
1549     errs() << "TypeID = " << Ty->getTypeID() << '\n';
1550     llvm_unreachable("Invalid type in printStaticConstant()");
1551   }
1552   // Increase offset.
1553   Offset += TySize;
1554 }
1555
1556
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);
1564     break;
1565   case Type::ArrayTyID:
1566   case Type::VectorTyID:
1567   case Type::StructTyID:
1568   case Type::PointerTyID:
1569     Out << getTypeName(C->getType());
1570     break;
1571   default:
1572     errs() << "Type = " << *C << "\n";
1573     llvm_unreachable("Invalid constant type");
1574   }
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);
1582   Out << "\n}\n\n";
1583 }
1584
1585
1586 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1587   const Constant* C = G->getInitializer();
1588   if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1589     InitListPtr = 0;
1590   else
1591     InitListPtr = &StaticInitList[G];
1592   printStaticInitializer(C,getValueName(G));
1593 }
1594
1595
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 " :
1602                                                      "private ");
1603     if (I->isDeclaration()) {
1604       Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1605     } else
1606       printVariableDefinition(&*I);
1607   }
1608 }
1609
1610
1611 const char* MSILWriter::getLibraryName(const Function* F) {
1612   return getLibraryForSymbol(F->getName(), true, F->getCallingConv());
1613 }
1614
1615
1616 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1617   return getLibraryForSymbol(GV->getName(), false, CallingConv::C);
1618 }
1619
1620
1621 const char* MSILWriter::getLibraryForSymbol(const StringRef &Name, 
1622                                             bool isFunction,
1623                                             CallingConv::ID CallingConv) {
1624   // TODO: Read *.def file with function and libraries definitions.
1625   return "MSVCRT.DLL";  
1626 }
1627
1628
1629 void MSILWriter::printExternals() {
1630   Module::const_iterator I,E;
1631   // Functions.
1632   for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1633     // Skip intrisics
1634     if (I->isIntrinsic()) continue;
1635     if (I->isDeclaration()) {
1636       const Function* F = I; 
1637       std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1638       std::string Sig = 
1639         getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1640       Out << ".method static hidebysig pinvokeimpl(\""
1641           << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1642     }
1643   }
1644   // External variables and static initialization.
1645   Out <<
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";
1650   Out <<
1651   ".method private static void* $MSIL_Import(string lib,string sym)\n"
1652   " managed cil\n{\n"
1653   "\tldarg\tlib\n"
1654   "\tcall\tnative int LoadLibrary(string)\n"
1655   "\tldarg\tsym\n"
1656   "\tcall\tnative int GetProcAddress(native int,string)\n"
1657   "\tdup\n"
1658   "\tbrtrue\tL_01\n"
1659   "\tldstr\t\"Can no import variable\"\n"
1660   "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1661   "\tthrow\n"
1662   "L_01:\n"
1663   "\tret\n"
1664   "}\n\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());
1678   }
1679   printSimpleInstruction("ret");
1680   Out << "}\n\n";
1681 }
1682
1683
1684 //===----------------------------------------------------------------------===//
1685 //                      External Interface declaration
1686 //===----------------------------------------------------------------------===//
1687
1688 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1689                                           formatted_raw_ostream &o,
1690                                           CodeGenFileType FileType,
1691                                           CodeGenOpt::Level OptLevel)
1692 {
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));
1700   PM.add(Writer);
1701   PM.add(createGCInfoDeleter());
1702   return false;
1703 }