llvm_unreachable->llvm_unreachable(0), LLVM_UNREACHABLE->llvm_unreachable.
[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/Transforms/Scalar.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/CodeGen/Passes.h"
28
29 namespace {
30   // TargetMachine for the MSIL 
31   struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
32     const TargetData DataLayout;       // Calculates type size & alignment
33
34     MSILTarget(const Module &M, const std::string &FS)
35       : DataLayout(&M) {}
36
37     virtual bool WantsWholeFile() const { return true; }
38     virtual bool addPassesToEmitWholeFile(PassManager &PM, raw_ostream &Out,
39                                           CodeGenFileType FileType,
40                                           CodeGenOpt::Level OptLevel);
41
42     // This class always works, but shouldn't be the default in most cases.
43     static unsigned getModuleMatchQuality(const Module &M) { return 1; }
44
45     virtual const TargetData *getTargetData() const { return &DataLayout; }
46   };
47 }
48
49 /// MSILTargetMachineModule - Note that this is used on hosts that
50 /// cannot link in a library unless there are references into the
51 /// library.  In particular, it seems that it is not possible to get
52 /// things to work on Win32 without this.  Though it is unused, do not
53 /// remove it.
54 extern "C" int MSILTargetMachineModule;
55 int MSILTargetMachineModule = 0;
56
57 static RegisterTarget<MSILTarget> X("msil", "MSIL backend");
58
59 // Force static initialization.
60 extern "C" void LLVMInitializeMSILTarget() { }
61
62 bool MSILModule::runOnModule(Module &M) {
63   ModulePtr = &M;
64   TD = &getAnalysis<TargetData>();
65   bool Changed = false;
66   // Find named types.  
67   TypeSymbolTable& Table = M.getTypeSymbolTable();
68   std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
69   for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
70     if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
71       Table.remove(I++);
72     else {
73       std::set<const Type *>::iterator T = Types.find(I->second);
74       if (T==Types.end())
75         Table.remove(I++);
76       else {
77         Types.erase(T);
78         ++I;
79       }
80     }
81   }
82   // Find unnamed types.
83   unsigned RenameCounter = 0;
84   for (std::set<const Type *>::const_iterator I = Types.begin(),
85        E = Types.end(); I!=E; ++I)
86     if (const StructType *STy = dyn_cast<StructType>(*I)) {
87       while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
88         ++RenameCounter;
89       Changed = true;
90     }
91   // Pointer for FunctionPass.
92   UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
93   return Changed;
94 }
95
96 char MSILModule::ID = 0;
97 char MSILWriter::ID = 0;
98
99 bool MSILWriter::runOnFunction(Function &F) {
100   if (F.isDeclaration()) return false;
101
102   // Do not codegen any 'available_externally' functions at all, they have
103   // definitions outside the translation unit.
104   if (F.hasAvailableExternallyLinkage())
105     return false;
106
107   LInfo = &getAnalysis<LoopInfo>();
108   printFunction(F);
109   return false;
110 }
111
112
113 bool MSILWriter::doInitialization(Module &M) {
114   ModulePtr = &M;
115   Mang = new Mangler(M);
116   Out << ".assembly extern mscorlib {}\n";
117   Out << ".assembly MSIL {}\n\n";
118   Out << "// External\n";
119   printExternals();
120   Out << "// Declarations\n";
121   printDeclarations(M.getTypeSymbolTable());
122   Out << "// Definitions\n";
123   printGlobalVariables();
124   Out << "// Startup code\n";
125   printModuleStartup();
126   return false;
127 }
128
129
130 bool MSILWriter::doFinalization(Module &M) {
131   delete Mang;
132   return false;
133 }
134
135
136 void MSILWriter::printModuleStartup() {
137   Out <<
138   ".method static public int32 $MSIL_Startup() {\n"
139   "\t.entrypoint\n"
140   "\t.locals (native int i)\n"
141   "\t.locals (native int argc)\n"
142   "\t.locals (native int ptr)\n"
143   "\t.locals (void* argv)\n"
144   "\t.locals (string[] args)\n"
145   "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
146   "\tdup\n"
147   "\tstloc\targs\n"
148   "\tldlen\n"
149   "\tconv.i4\n"
150   "\tdup\n"
151   "\tstloc\targc\n";
152   printPtrLoad(TD->getPointerSize());
153   Out <<
154   "\tmul\n"
155   "\tlocalloc\n"
156   "\tstloc\targv\n"
157   "\tldc.i4.0\n"
158   "\tstloc\ti\n"
159   "L_01:\n"
160   "\tldloc\ti\n"
161   "\tldloc\targc\n"
162   "\tceq\n"
163   "\tbrtrue\tL_02\n"
164   "\tldloc\targs\n"
165   "\tldloc\ti\n"
166   "\tldelem.ref\n"
167   "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
168            "StringToHGlobalAnsi(string)\n"
169   "\tstloc\tptr\n"
170   "\tldloc\targv\n"
171   "\tldloc\ti\n";
172   printPtrLoad(TD->getPointerSize());
173   Out << 
174   "\tmul\n"
175   "\tadd\n"
176   "\tldloc\tptr\n"
177   "\tstind.i\n"
178   "\tldloc\ti\n"
179   "\tldc.i4.1\n"
180   "\tadd\n"
181   "\tstloc\ti\n"
182   "\tbr\tL_01\n"
183   "L_02:\n"
184   "\tcall void $MSIL_Init()\n";
185
186   // Call user 'main' function.
187   const Function* F = ModulePtr->getFunction("main");
188   if (!F || F->isDeclaration()) {
189     Out << "\tldc.i4.0\n\tret\n}\n";
190     return;
191   }
192   bool BadSig = true;
193   std::string Args("");
194   Function::const_arg_iterator Arg1,Arg2;
195
196   switch (F->arg_size()) {
197   case 0:
198     BadSig = false;
199     break;
200   case 1:
201     Arg1 = F->arg_begin();
202     if (Arg1->getType()->isInteger()) {
203       Out << "\tldloc\targc\n";
204       Args = getTypeName(Arg1->getType());
205       BadSig = false;
206     }
207     break;
208   case 2:
209     Arg1 = Arg2 = F->arg_begin(); ++Arg2;
210     if (Arg1->getType()->isInteger() && 
211         Arg2->getType()->getTypeID() == Type::PointerTyID) {
212       Out << "\tldloc\targc\n\tldloc\targv\n";
213       Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
214       BadSig = false;
215     }
216     break;
217   default:
218     BadSig = true;
219   }
220
221   bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
222   if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
223     Out << "\tldc.i4.0\n";
224   } else {
225     Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
226       getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
227     if (RetVoid)
228       Out << "\tldc.i4.0\n";
229     else
230       Out << "\tconv.i4\n";
231   }
232   Out << "\tret\n}\n";
233 }
234
235 bool MSILWriter::isZeroValue(const Value* V) {
236   if (const Constant *C = dyn_cast<Constant>(V))
237     return C->isNullValue();
238   return false;
239 }
240
241
242 std::string MSILWriter::getValueName(const Value* V) {
243   std::string Name;
244   if (const GlobalValue *GV = cast<GlobalValue>(V))
245     Name = Mang->getValueName(GV);
246   else {
247     unsigned &No = AnonValueNumbers[V];
248     if (No == 0) No = ++NextAnonValueNumber;
249     Name = "tmp" + utostr(No);
250   }
251   
252   // Name into the quotes allow control and space characters.
253   return "'"+Name+"'";
254 }
255
256
257 std::string MSILWriter::getLabelName(const std::string& Name) {
258   if (Name.find('.')!=std::string::npos) {
259     std::string Tmp(Name);
260     // Replace unaccepable characters in the label name.
261     for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
262       if (*I=='.') *I = '@';
263     return Tmp;
264   }
265   return Name;
266 }
267
268
269 std::string MSILWriter::getLabelName(const Value* V) {
270   std::string Name;
271   if (const GlobalValue *GV = cast<GlobalValue>(V))
272     Name = Mang->getValueName(GV);
273   else {
274     unsigned &No = AnonValueNumbers[V];
275     if (No == 0) No = ++NextAnonValueNumber;
276     Name = "tmp" + utostr(No);
277   }
278   
279   return getLabelName(Name);
280 }
281
282
283 std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
284   switch (CallingConvID) {
285   case CallingConv::C:
286   case CallingConv::Cold:
287   case CallingConv::Fast:
288     return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
289   case CallingConv::X86_FastCall:
290     return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
291   case CallingConv::X86_StdCall:
292     return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
293   default:
294     cerr << "CallingConvID = " << CallingConvID << '\n';
295     llvm_unreachable("Unsupported calling convention");
296   }
297   return ""; // Not reached
298 }
299
300
301 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
302   std::string Tmp = "";
303   const Type* ElemTy = Ty;
304   assert(Ty->getTypeID()==TyID && "Invalid type passed");
305   // Walk trought array element types.
306   for (;;) {
307     // Multidimensional array.
308     if (ElemTy->getTypeID()==TyID) {
309       if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
310         Tmp += utostr(ATy->getNumElements());
311       else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
312         Tmp += utostr(VTy->getNumElements());
313       ElemTy = cast<SequentialType>(ElemTy)->getElementType();
314     }
315     // Base element type found.
316     if (ElemTy->getTypeID()!=TyID) break;
317     Tmp += ",";
318   }
319   return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
320 }
321
322
323 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
324   unsigned NumBits = 0;
325   switch (Ty->getTypeID()) {
326   case Type::VoidTyID:
327     return "void ";
328   case Type::IntegerTyID:
329     NumBits = getBitWidth(Ty);
330     if(NumBits==1)
331       return "bool ";
332     if (!isSigned)
333       return "unsigned int"+utostr(NumBits)+" ";
334     return "int"+utostr(NumBits)+" ";
335   case Type::FloatTyID:
336     return "float32 ";
337   case Type::DoubleTyID:
338     return "float64 "; 
339   default:
340     cerr << "Type = " << *Ty << '\n';
341     llvm_unreachable("Invalid primitive type");
342   }
343   return ""; // Not reached
344 }
345
346
347 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
348                                     bool isNested) {
349   if (Ty->isPrimitiveType() || Ty->isInteger())
350     return getPrimitiveTypeName(Ty,isSigned);
351   // FIXME: "OpaqueType" support
352   switch (Ty->getTypeID()) {
353   case Type::PointerTyID:
354     return "void* ";
355   case Type::StructTyID:
356     if (isNested)
357       return ModulePtr->getTypeName(Ty);
358     return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
359   case Type::ArrayTyID:
360     if (isNested)
361       return getArrayTypeName(Ty->getTypeID(),Ty);
362     return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
363   case Type::VectorTyID:
364     if (isNested)
365       return getArrayTypeName(Ty->getTypeID(),Ty);
366     return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
367   default:
368     cerr << "Type = " << *Ty << '\n';
369     llvm_unreachable("Invalid type in getTypeName()");
370   }
371   return ""; // Not reached
372 }
373
374
375 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
376   // Function argument
377   if (isa<Argument>(V))
378     return ArgumentVT;
379   // Function
380   else if (const Function* F = dyn_cast<Function>(V))
381     return F->hasLocalLinkage() ? InternalVT : GlobalVT;
382   // Variable
383   else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
384     return G->hasLocalLinkage() ? InternalVT : GlobalVT;
385   // Constant
386   else if (isa<Constant>(V))
387     return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
388   // Local variable
389   return LocalVT;
390 }
391
392
393 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
394                                        bool isSigned) {
395   unsigned NumBits = 0;
396   switch (Ty->getTypeID()) {
397   // Integer constant, expanding for stack operations.
398   case Type::IntegerTyID:
399     NumBits = getBitWidth(Ty);
400     // Expand integer value to "int32" or "int64".
401     if (Expand) return (NumBits<=32 ? "i4" : "i8");
402     if (NumBits==1) return "i1";
403     return (isSigned ? "i" : "u")+utostr(NumBits/8);
404   // Float constant.
405   case Type::FloatTyID:
406     return "r4";
407   case Type::DoubleTyID:
408     return "r8";
409   case Type::PointerTyID:
410     return "i"+utostr(TD->getTypeAllocSize(Ty));
411   default:
412     cerr << "TypeID = " << Ty->getTypeID() << '\n';
413     llvm_unreachable("Invalid type in TypeToPostfix()");
414   }
415   return ""; // Not reached
416 }
417
418
419 void MSILWriter::printConvToPtr() {
420   switch (ModulePtr->getPointerSize()) {
421   case Module::Pointer32:
422     printSimpleInstruction("conv.u4");
423     break;
424   case Module::Pointer64:
425     printSimpleInstruction("conv.u8");
426     break;
427   default:
428     llvm_unreachable("Module use not supporting pointer size");
429   }
430 }
431
432
433 void MSILWriter::printPtrLoad(uint64_t N) {
434   switch (ModulePtr->getPointerSize()) {
435   case Module::Pointer32:
436     printSimpleInstruction("ldc.i4",utostr(N).c_str());
437     // FIXME: Need overflow test?
438     if (!isUInt32(N)) {
439       cerr << "Value = " << utostr(N) << '\n';
440       llvm_unreachable("32-bit pointer overflowed");
441     }
442     break;
443   case Module::Pointer64:
444     printSimpleInstruction("ldc.i8",utostr(N).c_str());
445     break;
446   default:
447     llvm_unreachable("Module use not supporting pointer size");
448   }
449 }
450
451
452 void MSILWriter::printValuePtrLoad(const Value* V) {
453   printValueLoad(V);
454   printConvToPtr();
455 }
456
457
458 void MSILWriter::printConstLoad(const Constant* C) {
459   if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
460     // Integer constant
461     Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
462     if (CInt->isMinValue(true))
463       Out << CInt->getSExtValue();
464     else
465       Out << CInt->getZExtValue();
466   } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
467     // Float constant
468     uint64_t X;
469     unsigned Size;
470     if (FP->getType()->getTypeID()==Type::FloatTyID) {
471       X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
472       Size = 4;  
473     } else {
474       X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
475       Size = 8;  
476     }
477     Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
478   } else if (isa<UndefValue>(C)) {
479     // Undefined constant value = NULL.
480     printPtrLoad(0);
481   } else {
482     cerr << "Constant = " << *C << '\n';
483     llvm_unreachable("Invalid constant value");
484   }
485   Out << '\n';
486 }
487
488
489 void MSILWriter::printValueLoad(const Value* V) {
490   MSILWriter::ValueType Location = getValueLocation(V);
491   switch (Location) {
492   // Global variable or function address.
493   case GlobalVT:
494   case InternalVT:
495     if (const Function* F = dyn_cast<Function>(V)) {
496       std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
497       printSimpleInstruction("ldftn",
498         getCallSignature(F->getFunctionType(),NULL,Name).c_str());
499     } else {
500       std::string Tmp;
501       const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
502       if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
503         Tmp = "void* "+getValueName(V);
504         printSimpleInstruction("ldsfld",Tmp.c_str());
505       } else {
506         Tmp = getTypeName(ElemTy)+getValueName(V);
507         printSimpleInstruction("ldsflda",Tmp.c_str());
508       }
509     }
510     break;
511   // Function argument.
512   case ArgumentVT:
513     printSimpleInstruction("ldarg",getValueName(V).c_str());
514     break;
515   // Local function variable.
516   case LocalVT:
517     printSimpleInstruction("ldloc",getValueName(V).c_str());
518     break;
519   // Constant value.
520   case ConstVT:
521     if (isa<ConstantPointerNull>(V))
522       printPtrLoad(0);
523     else
524       printConstLoad(cast<Constant>(V));
525     break;
526   // Constant expression.
527   case ConstExprVT:
528     printConstantExpr(cast<ConstantExpr>(V));
529     break;
530   default:
531     cerr << "Value = " << *V << '\n';
532     llvm_unreachable("Invalid value location");
533   }
534 }
535
536
537 void MSILWriter::printValueSave(const Value* V) {
538   switch (getValueLocation(V)) {
539   case ArgumentVT:
540     printSimpleInstruction("starg",getValueName(V).c_str());
541     break;
542   case LocalVT:
543     printSimpleInstruction("stloc",getValueName(V).c_str());
544     break;
545   default:
546     cerr << "Value  = " << *V << '\n';
547     llvm_unreachable("Invalid value location");
548   }
549 }
550
551
552 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
553                                         const Value* Right) {
554   printValueLoad(Left);
555   printValueLoad(Right);
556   Out << '\t' << Name << '\n';
557 }
558
559
560 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
561   if(Operand) 
562     Out << '\t' << Inst << '\t' << Operand << '\n';
563   else
564     Out << '\t' << Inst << '\n';
565 }
566
567
568 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
569   for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
570        isa<PHINode>(I); ++I) {
571     const PHINode* Phi = cast<PHINode>(I);
572     const Value* Val = Phi->getIncomingValueForBlock(Src);
573     if (isa<UndefValue>(Val)) continue;
574     printValueLoad(Val);
575     printValueSave(Phi);
576   }
577 }
578
579
580 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
581                                     const BasicBlock* TrueBB,
582                                     const BasicBlock* FalseBB) {
583   if (TrueBB==FalseBB) {
584     // "TrueBB" and "FalseBB" destination equals
585     printPHICopy(CurrBB,TrueBB);
586     printSimpleInstruction("pop");
587     printSimpleInstruction("br",getLabelName(TrueBB).c_str());
588   } else if (FalseBB==NULL) {
589     // If "FalseBB" not used the jump have condition
590     printPHICopy(CurrBB,TrueBB);
591     printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
592   } else if (TrueBB==NULL) {
593     // If "TrueBB" not used the jump is unconditional
594     printPHICopy(CurrBB,FalseBB);
595     printSimpleInstruction("br",getLabelName(FalseBB).c_str());
596   } else {
597     // Copy PHI instructions for each block
598     std::string TmpLabel;
599     // Print PHI instructions for "TrueBB"
600     if (isa<PHINode>(TrueBB->begin())) {
601       TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
602       printSimpleInstruction("brtrue",TmpLabel.c_str());
603     } else {
604       printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
605     }
606     // Print PHI instructions for "FalseBB"
607     if (isa<PHINode>(FalseBB->begin())) {
608       printPHICopy(CurrBB,FalseBB);
609       printSimpleInstruction("br",getLabelName(FalseBB).c_str());
610     } else {
611       printSimpleInstruction("br",getLabelName(FalseBB).c_str());
612     }
613     if (isa<PHINode>(TrueBB->begin())) {
614       // Handle "TrueBB" PHI Copy
615       Out << TmpLabel << ":\n";
616       printPHICopy(CurrBB,TrueBB);
617       printSimpleInstruction("br",getLabelName(TrueBB).c_str());
618     }
619   }
620 }
621
622
623 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
624   if (Inst->isUnconditional()) {
625     printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
626   } else {
627     printValueLoad(Inst->getCondition());
628     printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
629                        Inst->getSuccessor(1));
630   }
631 }
632
633
634 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
635                                         const Value* VFalse) {
636   std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
637   printValueLoad(VTrue);
638   printValueLoad(Cond);
639   printSimpleInstruction("brtrue",TmpLabel.c_str());
640   printSimpleInstruction("pop");
641   printValueLoad(VFalse);
642   Out << TmpLabel << ":\n";
643 }
644
645
646 void MSILWriter::printIndirectLoad(const Value* V) {
647   const Type* Ty = V->getType();
648   printValueLoad(V);
649   if (const PointerType* P = dyn_cast<PointerType>(Ty))
650     Ty = P->getElementType();
651   std::string Tmp = "ldind."+getTypePostfix(Ty, false);
652   printSimpleInstruction(Tmp.c_str());
653 }
654
655
656 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
657   printValueLoad(Ptr);
658   printValueLoad(Val);
659   printIndirectSave(Val->getType());
660 }
661
662
663 void MSILWriter::printIndirectSave(const Type* Ty) {
664   // Instruction need signed postfix for any type.
665   std::string postfix = getTypePostfix(Ty, false);
666   if (*postfix.begin()=='u') *postfix.begin() = 'i';
667   postfix = "stind."+postfix;
668   printSimpleInstruction(postfix.c_str());
669 }
670
671
672 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
673                                       const Type* Ty, const Type* SrcTy) {
674   std::string Tmp("");
675   printValueLoad(V);
676   switch (Op) {
677   // Signed
678   case Instruction::SExt:
679     // If sign extending int, convert first from unsigned to signed
680     // with the same bit size - because otherwise we will loose the sign.
681     if (SrcTy) {
682       Tmp = "conv."+getTypePostfix(SrcTy,false,true);
683       printSimpleInstruction(Tmp.c_str());
684     }
685   case Instruction::SIToFP:
686   case Instruction::FPToSI:
687     Tmp = "conv."+getTypePostfix(Ty,false,true);
688     printSimpleInstruction(Tmp.c_str());
689     break;
690   // Unsigned
691   case Instruction::FPTrunc:
692   case Instruction::FPExt:
693   case Instruction::UIToFP:
694   case Instruction::Trunc:
695   case Instruction::ZExt:
696   case Instruction::FPToUI:
697   case Instruction::PtrToInt:
698   case Instruction::IntToPtr:
699     Tmp = "conv."+getTypePostfix(Ty,false);
700     printSimpleInstruction(Tmp.c_str());
701     break;
702   // Do nothing
703   case Instruction::BitCast:
704     // FIXME: meaning that ld*/st* instruction do not change data format.
705     break;
706   default:
707     cerr << "Opcode = " << Op << '\n';
708     llvm_unreachable("Invalid conversion instruction");
709   }
710 }
711
712
713 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
714                                      gep_type_iterator E) {
715   unsigned Size;
716   // Load address
717   printValuePtrLoad(V);
718   // Calculate element offset.
719   for (; I!=E; ++I){
720     Size = 0;
721     const Value* IndexValue = I.getOperand();
722     if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
723       uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
724       // Offset is the sum of all previous structure fields.
725       for (uint64_t F = 0; F<FieldIndex; ++F)
726         Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
727       printPtrLoad(Size);
728       printSimpleInstruction("add");
729       continue;
730     } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
731       Size = TD->getTypeAllocSize(SeqTy->getElementType());
732     } else {
733       Size = TD->getTypeAllocSize(*I);
734     }
735     // Add offset of current element to stack top.
736     if (!isZeroValue(IndexValue)) {
737       // Constant optimization.
738       if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
739         if (C->getValue().isNegative()) {
740           printPtrLoad(C->getValue().abs().getZExtValue()*Size);
741           printSimpleInstruction("sub");
742           continue;
743         } else
744           printPtrLoad(C->getZExtValue()*Size);
745       } else {
746         printPtrLoad(Size);
747         printValuePtrLoad(IndexValue);
748         printSimpleInstruction("mul");
749       }
750       printSimpleInstruction("add");
751     }
752   }
753 }
754
755
756 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
757                                          const Instruction* Inst,
758                                          std::string Name) {
759   std::string Tmp("");
760   if (Ty->isVarArg()) Tmp += "vararg ";
761   // Name and return type.
762   Tmp += getTypeName(Ty->getReturnType())+Name+"(";
763   // Function argument type list.
764   unsigned NumParams = Ty->getNumParams();
765   for (unsigned I = 0; I!=NumParams; ++I) {
766     if (I!=0) Tmp += ",";
767     Tmp += getTypeName(Ty->getParamType(I));
768   }
769   // CLR needs to know the exact amount of parameters received by vararg
770   // function, because caller cleans the stack.
771   if (Ty->isVarArg() && Inst) {
772     // Origin to function arguments in "CallInst" or "InvokeInst".
773     unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
774     // Print variable argument types.
775     unsigned NumOperands = Inst->getNumOperands()-Org;
776     if (NumParams<NumOperands) {
777       if (NumParams!=0) Tmp += ", ";
778       Tmp += "... , ";
779       for (unsigned J = NumParams; J!=NumOperands; ++J) {
780         if (J!=NumParams) Tmp += ", ";
781         Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
782       }
783     }
784   }
785   return Tmp+")";
786 }
787
788
789 void MSILWriter::printFunctionCall(const Value* FnVal,
790                                    const Instruction* Inst) {
791   // Get function calling convention.
792   std::string Name = "";
793   if (const CallInst* Call = dyn_cast<CallInst>(Inst))
794     Name = getConvModopt(Call->getCallingConv());
795   else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
796     Name = getConvModopt(Invoke->getCallingConv());
797   else {
798     cerr << "Instruction = " << Inst->getName() << '\n';
799     llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
800   }
801   if (const Function* F = dyn_cast<Function>(FnVal)) {
802     // Direct call.
803     Name += getValueName(F);
804     printSimpleInstruction("call",
805       getCallSignature(F->getFunctionType(),Inst,Name).c_str());
806   } else {
807     // Indirect function call.
808     const PointerType* PTy = cast<PointerType>(FnVal->getType());
809     const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
810     // Load function address.
811     printValueLoad(FnVal);
812     printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
813   }
814 }
815
816
817 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
818   std::string Name;
819   switch (Inst->getIntrinsicID()) {
820   case Intrinsic::vastart:
821     Name = getValueName(Inst->getOperand(1));
822     Name.insert(Name.length()-1,"$valist");
823     // Obtain the argument handle.
824     printSimpleInstruction("ldloca",Name.c_str());
825     printSimpleInstruction("arglist");
826     printSimpleInstruction("call",
827       "instance void [mscorlib]System.ArgIterator::.ctor"
828       "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
829     // Save as pointer type "void*"
830     printValueLoad(Inst->getOperand(1));
831     printSimpleInstruction("ldloca",Name.c_str());
832     printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
833     break;
834   case Intrinsic::vaend:
835     // Close argument list handle.
836     printIndirectLoad(Inst->getOperand(1));
837     printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
838     break;
839   case Intrinsic::vacopy:
840     // Copy "ArgIterator" valuetype.
841     printIndirectLoad(Inst->getOperand(1));
842     printIndirectLoad(Inst->getOperand(2));
843     printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
844     break;        
845   default:
846     cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
847     llvm_unreachable("Invalid intrinsic function");
848   }
849 }
850
851
852 void MSILWriter::printCallInstruction(const Instruction* Inst) {
853   if (isa<IntrinsicInst>(Inst)) {
854     // Handle intrinsic function.
855     printIntrinsicCall(cast<IntrinsicInst>(Inst));
856   } else {
857     // Load arguments to stack and call function.
858     for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
859       printValueLoad(Inst->getOperand(I));
860     printFunctionCall(Inst->getOperand(0),Inst);
861   }
862 }
863
864
865 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
866                                       const Value* Right) {
867   switch (Predicate) {
868   case ICmpInst::ICMP_EQ:
869     printBinaryInstruction("ceq",Left,Right);
870     break;
871   case ICmpInst::ICMP_NE:
872     // Emulate = not neg (Op1 eq Op2)
873     printBinaryInstruction("ceq",Left,Right);
874     printSimpleInstruction("neg");
875     printSimpleInstruction("not");
876     break;
877   case ICmpInst::ICMP_ULE:
878   case ICmpInst::ICMP_SLE:
879     // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
880     printBinaryInstruction("ceq",Left,Right);
881     if (Predicate==ICmpInst::ICMP_ULE)
882       printBinaryInstruction("clt.un",Left,Right);
883     else
884       printBinaryInstruction("clt",Left,Right);
885     printSimpleInstruction("or");
886     break;
887   case ICmpInst::ICMP_UGE:
888   case ICmpInst::ICMP_SGE:
889     // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
890     printBinaryInstruction("ceq",Left,Right);
891     if (Predicate==ICmpInst::ICMP_UGE)
892       printBinaryInstruction("cgt.un",Left,Right);
893     else
894       printBinaryInstruction("cgt",Left,Right);
895     printSimpleInstruction("or");
896     break;
897   case ICmpInst::ICMP_ULT:
898     printBinaryInstruction("clt.un",Left,Right);
899     break;
900   case ICmpInst::ICMP_SLT:
901     printBinaryInstruction("clt",Left,Right);
902     break;
903   case ICmpInst::ICMP_UGT:
904     printBinaryInstruction("cgt.un",Left,Right);
905     break;
906   case ICmpInst::ICMP_SGT:
907     printBinaryInstruction("cgt",Left,Right);
908     break;
909   default:
910     cerr << "Predicate = " << Predicate << '\n';
911     llvm_unreachable("Invalid icmp predicate");
912   }
913 }
914
915
916 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
917                                       const Value* Right) {
918   // FIXME: Correct comparison
919   std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
920   switch (Predicate) {
921   case FCmpInst::FCMP_UGT:
922     // X >  Y || llvm_fcmp_uno(X, Y)
923     printBinaryInstruction("cgt",Left,Right);
924     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
925     printSimpleInstruction("or");
926     break;
927   case FCmpInst::FCMP_OGT:
928     // X >  Y
929     printBinaryInstruction("cgt",Left,Right);
930     break;
931   case FCmpInst::FCMP_UGE:
932     // X >= Y || llvm_fcmp_uno(X, Y)
933     printBinaryInstruction("ceq",Left,Right);
934     printBinaryInstruction("cgt",Left,Right);
935     printSimpleInstruction("or");
936     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
937     printSimpleInstruction("or");
938     break;
939   case FCmpInst::FCMP_OGE:
940     // X >= Y
941     printBinaryInstruction("ceq",Left,Right);
942     printBinaryInstruction("cgt",Left,Right);
943     printSimpleInstruction("or");
944     break;
945   case FCmpInst::FCMP_ULT:
946     // X <  Y || llvm_fcmp_uno(X, Y)
947     printBinaryInstruction("clt",Left,Right);
948     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
949     printSimpleInstruction("or");
950     break;
951   case FCmpInst::FCMP_OLT:
952     // X <  Y
953     printBinaryInstruction("clt",Left,Right);
954     break;
955   case FCmpInst::FCMP_ULE:
956     // X <= Y || llvm_fcmp_uno(X, Y)
957     printBinaryInstruction("ceq",Left,Right);
958     printBinaryInstruction("clt",Left,Right);
959     printSimpleInstruction("or");
960     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
961     printSimpleInstruction("or");
962     break;
963   case FCmpInst::FCMP_OLE:
964     // X <= Y
965     printBinaryInstruction("ceq",Left,Right);
966     printBinaryInstruction("clt",Left,Right);
967     printSimpleInstruction("or");
968     break;
969   case FCmpInst::FCMP_UEQ:
970     // X == Y || llvm_fcmp_uno(X, Y)
971     printBinaryInstruction("ceq",Left,Right);
972     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
973     printSimpleInstruction("or");
974     break;
975   case FCmpInst::FCMP_OEQ:
976     // X == Y
977     printBinaryInstruction("ceq",Left,Right);
978     break;
979   case FCmpInst::FCMP_UNE:
980     // X != Y
981     printBinaryInstruction("ceq",Left,Right);
982     printSimpleInstruction("neg");
983     printSimpleInstruction("not");
984     break;
985   case FCmpInst::FCMP_ONE:
986     // X != Y && llvm_fcmp_ord(X, Y)
987     printBinaryInstruction("ceq",Left,Right);
988     printSimpleInstruction("not");
989     break;
990   case FCmpInst::FCMP_ORD:
991     // return X == X && Y == Y
992     printBinaryInstruction("ceq",Left,Left);
993     printBinaryInstruction("ceq",Right,Right);
994     printSimpleInstruction("or");
995     break;
996   case FCmpInst::FCMP_UNO:
997     // X != X || Y != Y
998     printBinaryInstruction("ceq",Left,Left);
999     printSimpleInstruction("not");
1000     printBinaryInstruction("ceq",Right,Right);
1001     printSimpleInstruction("not");
1002     printSimpleInstruction("or");
1003     break;
1004   default:
1005     llvm_unreachable("Illegal FCmp predicate");
1006   }
1007 }
1008
1009
1010 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1011   std::string Label = "leave$normal_"+utostr(getUniqID());
1012   Out << ".try {\n";
1013   // Load arguments
1014   for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1015     printValueLoad(Inst->getOperand(I));
1016   // Print call instruction
1017   printFunctionCall(Inst->getOperand(0),Inst);
1018   // Save function result and leave "try" block
1019   printValueSave(Inst);
1020   printSimpleInstruction("leave",Label.c_str());
1021   Out << "}\n";
1022   Out << "catch [mscorlib]System.Exception {\n";
1023   // Redirect to unwind block
1024   printSimpleInstruction("pop");
1025   printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1026   Out << "}\n" << Label << ":\n";
1027   // Redirect to continue block
1028   printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1029 }
1030
1031
1032 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1033   // FIXME: Emulate with IL "switch" instruction
1034   // Emulate = if () else if () else if () else ...
1035   for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1036     printValueLoad(Inst->getCondition());
1037     printValueLoad(Inst->getCaseValue(I));
1038     printSimpleInstruction("ceq");
1039     // Condition jump to successor block
1040     printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1041   }
1042   // Jump to default block
1043   printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1044 }
1045
1046
1047 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1048   printIndirectLoad(Inst->getOperand(0));
1049   printSimpleInstruction("call",
1050     "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1051   printSimpleInstruction("refanyval","void*");
1052   std::string Name = 
1053     "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
1054   printSimpleInstruction(Name.c_str());
1055 }
1056
1057
1058 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
1059   uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
1060   // Constant optimization.
1061   if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1062     printPtrLoad(CInt->getZExtValue()*Size);
1063   } else {
1064     printPtrLoad(Size);
1065     printValueLoad(Inst->getOperand(0));
1066     printSimpleInstruction("mul");
1067   }
1068   printSimpleInstruction("localloc");
1069 }
1070
1071
1072 void MSILWriter::printInstruction(const Instruction* Inst) {
1073   const Value *Left = 0, *Right = 0;
1074   if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1075   if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1076   // Print instruction
1077   // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
1078   switch (Inst->getOpcode()) {
1079   // Terminator
1080   case Instruction::Ret:
1081     if (Inst->getNumOperands()) {
1082       printValueLoad(Left);
1083       printSimpleInstruction("ret");
1084     } else
1085       printSimpleInstruction("ret");
1086     break;
1087   case Instruction::Br:
1088     printBranchInstruction(cast<BranchInst>(Inst));
1089     break;
1090   // Binary
1091   case Instruction::Add:
1092   case Instruction::FAdd:
1093     printBinaryInstruction("add",Left,Right);
1094     break;
1095   case Instruction::Sub:
1096   case Instruction::FSub:
1097     printBinaryInstruction("sub",Left,Right);
1098     break;
1099   case Instruction::Mul:
1100   case Instruction::FMul:
1101     printBinaryInstruction("mul",Left,Right);
1102     break;
1103   case Instruction::UDiv:
1104     printBinaryInstruction("div.un",Left,Right);
1105     break;
1106   case Instruction::SDiv:
1107   case Instruction::FDiv:
1108     printBinaryInstruction("div",Left,Right);
1109     break;
1110   case Instruction::URem:
1111     printBinaryInstruction("rem.un",Left,Right);
1112     break;
1113   case Instruction::SRem:
1114   case Instruction::FRem:
1115     printBinaryInstruction("rem",Left,Right);
1116     break;
1117   // Binary Condition
1118   case Instruction::ICmp:
1119     printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1120     break;
1121   case Instruction::FCmp:
1122     printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1123     break;
1124   // Bitwise Binary
1125   case Instruction::And:
1126     printBinaryInstruction("and",Left,Right);
1127     break;
1128   case Instruction::Or:
1129     printBinaryInstruction("or",Left,Right);
1130     break;
1131   case Instruction::Xor:
1132     printBinaryInstruction("xor",Left,Right);
1133     break;
1134   case Instruction::Shl:
1135     printValueLoad(Left);
1136     printValueLoad(Right);
1137     printSimpleInstruction("conv.i4");
1138     printSimpleInstruction("shl");
1139     break;
1140   case Instruction::LShr:
1141     printValueLoad(Left);
1142     printValueLoad(Right);
1143     printSimpleInstruction("conv.i4");
1144     printSimpleInstruction("shr.un");
1145     break;
1146   case Instruction::AShr:
1147     printValueLoad(Left);
1148     printValueLoad(Right);
1149     printSimpleInstruction("conv.i4");
1150     printSimpleInstruction("shr");
1151     break;
1152   case Instruction::Select:
1153     printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1154     break;
1155   case Instruction::Load:
1156     printIndirectLoad(Inst->getOperand(0));
1157     break;
1158   case Instruction::Store:
1159     printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1160     break;
1161   case Instruction::SExt:
1162     printCastInstruction(Inst->getOpcode(),Left,
1163                          cast<CastInst>(Inst)->getDestTy(),
1164                          cast<CastInst>(Inst)->getSrcTy());
1165     break;
1166   case Instruction::Trunc:
1167   case Instruction::ZExt:
1168   case Instruction::FPTrunc:
1169   case Instruction::FPExt:
1170   case Instruction::UIToFP:
1171   case Instruction::SIToFP:
1172   case Instruction::FPToUI:
1173   case Instruction::FPToSI:
1174   case Instruction::PtrToInt:
1175   case Instruction::IntToPtr:
1176   case Instruction::BitCast:
1177     printCastInstruction(Inst->getOpcode(),Left,
1178                          cast<CastInst>(Inst)->getDestTy());
1179     break;
1180   case Instruction::GetElementPtr:
1181     printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1182                         gep_type_end(Inst));
1183     break;
1184   case Instruction::Call:
1185     printCallInstruction(cast<CallInst>(Inst));
1186     break;
1187   case Instruction::Invoke:
1188     printInvokeInstruction(cast<InvokeInst>(Inst));
1189     break;
1190   case Instruction::Unwind:
1191     printSimpleInstruction("newobj",
1192       "instance void [mscorlib]System.Exception::.ctor()");
1193     printSimpleInstruction("throw");
1194     break;
1195   case Instruction::Switch:
1196     printSwitchInstruction(cast<SwitchInst>(Inst));
1197     break;
1198   case Instruction::Alloca:
1199     printAllocaInstruction(cast<AllocaInst>(Inst));
1200     break;
1201   case Instruction::Malloc:
1202     llvm_unreachable("LowerAllocationsPass used");
1203     break;
1204   case Instruction::Free:
1205     llvm_unreachable("LowerAllocationsPass used");
1206     break;
1207   case Instruction::Unreachable:
1208     printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1209     printSimpleInstruction("newobj",
1210       "instance void [mscorlib]System.Exception::.ctor(string)");
1211     printSimpleInstruction("throw");
1212     break;
1213   case Instruction::VAArg:
1214     printVAArgInstruction(cast<VAArgInst>(Inst));
1215     break;
1216   default:
1217     cerr << "Instruction = " << Inst->getName() << '\n';
1218     llvm_unreachable("Unsupported instruction");
1219   }
1220 }
1221
1222
1223 void MSILWriter::printLoop(const Loop* L) {
1224   Out << getLabelName(L->getHeader()->getName()) << ":\n";
1225   const std::vector<BasicBlock*>& blocks = L->getBlocks();
1226   for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1227     BasicBlock* BB = blocks[I];
1228     Loop* BBLoop = LInfo->getLoopFor(BB);
1229     if (BBLoop == L)
1230       printBasicBlock(BB);
1231     else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1232       printLoop(BBLoop);
1233   }
1234   printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1235 }
1236
1237
1238 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1239   Out << getLabelName(BB) << ":\n";
1240   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1241     const Instruction* Inst = I;
1242     // Comment llvm original instruction
1243     // Out << "\n//" << *Inst << "\n";
1244     // Do not handle PHI instruction in current block
1245     if (Inst->getOpcode()==Instruction::PHI) continue;
1246     // Print instruction
1247     printInstruction(Inst);
1248     // Save result
1249     if (Inst->getType()!=Type::VoidTy) {
1250       // Do not save value after invoke, it done in "try" block
1251       if (Inst->getOpcode()==Instruction::Invoke) continue;
1252       printValueSave(Inst);
1253     }
1254   }
1255 }
1256
1257
1258 void MSILWriter::printLocalVariables(const Function& F) {
1259   std::string Name;
1260   const Type* Ty = NULL;
1261   std::set<const Value*> Printed;
1262   const Value* VaList = NULL;
1263   unsigned StackDepth = 8;
1264   // Find local variables
1265   for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
1266     if (I->getOpcode()==Instruction::Call ||
1267         I->getOpcode()==Instruction::Invoke) {
1268       // Test stack depth.
1269       if (StackDepth<I->getNumOperands())
1270         StackDepth = I->getNumOperands();
1271     }
1272     const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1273     if (AI && !isa<GlobalVariable>(AI)) {
1274       // Local variable allocation.
1275       Ty = PointerType::getUnqual(AI->getAllocatedType());
1276       Name = getValueName(AI);
1277       Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1278     } else if (I->getType()!=Type::VoidTy) {
1279       // Operation result.
1280       Ty = I->getType();
1281       Name = getValueName(&*I);
1282       Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1283     }
1284     // Test on 'va_list' variable    
1285     bool isVaList = false;     
1286     if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1287       // "va_list" as "va_arg" instruction operand.
1288       isVaList = true;
1289       VaList = VaInst->getOperand(0);
1290     } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1291       // "va_list" as intrinsic function operand. 
1292       switch (Inst->getIntrinsicID()) {
1293       case Intrinsic::vastart:
1294       case Intrinsic::vaend:
1295       case Intrinsic::vacopy:
1296         isVaList = true;
1297         VaList = Inst->getOperand(1);
1298         break;
1299       default:
1300         isVaList = false;
1301       }
1302     }
1303     // Print "va_list" variable.
1304     if (isVaList && Printed.insert(VaList).second) {
1305       Name = getValueName(VaList);
1306       Name.insert(Name.length()-1,"$valist");
1307       Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1308           << Name << ")\n";
1309     }
1310   }
1311   printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1312 }
1313
1314
1315 void MSILWriter::printFunctionBody(const Function& F) {
1316   // Print body
1317   for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1318     if (Loop *L = LInfo->getLoopFor(I)) {
1319       if (L->getHeader()==I && L->getParentLoop()==0)
1320         printLoop(L);
1321     } else {
1322       printBasicBlock(I);
1323     }
1324   }
1325 }
1326
1327
1328 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1329   const Value *left = 0, *right = 0;
1330   if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1331   if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1332   // Print instruction
1333   switch (CE->getOpcode()) {
1334   case Instruction::Trunc:
1335   case Instruction::ZExt:
1336   case Instruction::SExt:
1337   case Instruction::FPTrunc:
1338   case Instruction::FPExt:
1339   case Instruction::UIToFP:
1340   case Instruction::SIToFP:
1341   case Instruction::FPToUI:
1342   case Instruction::FPToSI:
1343   case Instruction::PtrToInt:
1344   case Instruction::IntToPtr:
1345   case Instruction::BitCast:
1346     printCastInstruction(CE->getOpcode(),left,CE->getType());
1347     break;
1348   case Instruction::GetElementPtr:
1349     printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1350     break;
1351   case Instruction::ICmp:
1352     printICmpInstruction(CE->getPredicate(),left,right);
1353     break;
1354   case Instruction::FCmp:
1355     printFCmpInstruction(CE->getPredicate(),left,right);
1356     break;
1357   case Instruction::Select:
1358     printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1359     break;
1360   case Instruction::Add:
1361   case Instruction::FAdd:
1362     printBinaryInstruction("add",left,right);
1363     break;
1364   case Instruction::Sub:
1365   case Instruction::FSub:
1366     printBinaryInstruction("sub",left,right);
1367     break;
1368   case Instruction::Mul:
1369   case Instruction::FMul:
1370     printBinaryInstruction("mul",left,right);
1371     break;
1372   case Instruction::UDiv:
1373     printBinaryInstruction("div.un",left,right);
1374     break;
1375   case Instruction::SDiv:
1376   case Instruction::FDiv:
1377     printBinaryInstruction("div",left,right);
1378     break;
1379   case Instruction::URem:
1380     printBinaryInstruction("rem.un",left,right);
1381     break;
1382   case Instruction::SRem:
1383   case Instruction::FRem:
1384     printBinaryInstruction("rem",left,right);
1385     break;
1386   case Instruction::And:
1387     printBinaryInstruction("and",left,right);
1388     break;
1389   case Instruction::Or:
1390     printBinaryInstruction("or",left,right);
1391     break;
1392   case Instruction::Xor:
1393     printBinaryInstruction("xor",left,right);
1394     break;
1395   case Instruction::Shl:
1396     printBinaryInstruction("shl",left,right);
1397     break;
1398   case Instruction::LShr:
1399     printBinaryInstruction("shr.un",left,right);
1400     break;
1401   case Instruction::AShr:
1402     printBinaryInstruction("shr",left,right);
1403     break;
1404   default:
1405     cerr << "Expression = " << *CE << "\n";
1406     llvm_unreachable("Invalid constant expression");
1407   }
1408 }
1409
1410
1411 void MSILWriter::printStaticInitializerList() {
1412   // List of global variables with uninitialized fields.
1413   for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1414        VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1415        ++VarI) {
1416     const std::vector<StaticInitializer>& InitList = VarI->second;
1417     if (InitList.empty()) continue;
1418     // For each uninitialized field.
1419     for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1420          E = InitList.end(); I!=E; ++I) {
1421       if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
1422         // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1423         //  utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
1424         // Load variable address
1425         printValueLoad(VarI->first);
1426         // Add offset
1427         if (I->offset!=0) {
1428           printPtrLoad(I->offset);
1429           printSimpleInstruction("add");
1430         }
1431         // Load value
1432         printConstantExpr(CE);
1433         // Save result at offset
1434         std::string postfix = getTypePostfix(CE->getType(),true);
1435         if (*postfix.begin()=='u') *postfix.begin() = 'i';
1436         postfix = "stind."+postfix;
1437         printSimpleInstruction(postfix.c_str());
1438       } else {
1439         cerr << "Constant = " << *I->constant << '\n';
1440         llvm_unreachable("Invalid static initializer");
1441       }
1442     }
1443   }
1444 }
1445
1446
1447 void MSILWriter::printFunction(const Function& F) {
1448   bool isSigned = F.paramHasAttr(0, Attribute::SExt);
1449   Out << "\n.method static ";
1450   Out << (F.hasLocalLinkage() ? "private " : "public ");
1451   if (F.isVarArg()) Out << "vararg ";
1452   Out << getTypeName(F.getReturnType(),isSigned) << 
1453     getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1454   // Arguments
1455   Out << "\t(";
1456   unsigned ArgIdx = 1;
1457   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1458        ++I, ++ArgIdx) {
1459     isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
1460     if (I!=F.arg_begin()) Out << ", ";
1461     Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1462   }
1463   Out << ") cil managed\n";
1464   // Body
1465   Out << "{\n";
1466   printLocalVariables(F);
1467   printFunctionBody(F);
1468   Out << "}\n";
1469 }
1470
1471
1472 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1473   std::string Name;
1474   std::set<const Type*> Printed;
1475   for (std::set<const Type*>::const_iterator
1476        UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1477     const Type* Ty = *UI;
1478     if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1479       Name = getTypeName(Ty, false, true);
1480     // Type with no need to declare.
1481     else continue;
1482     // Print not duplicated type
1483     if (Printed.insert(Ty).second) {
1484       Out << ".class value explicit ansi sealed '" << Name << "'";
1485       Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
1486       Out << " }\n\n";
1487     }
1488   }
1489 }
1490
1491
1492 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1493   unsigned int N = Ty->getPrimitiveSizeInBits();
1494   assert(N!=0 && "Invalid type in getBitWidth()");
1495   switch (N) {
1496   case 1:
1497   case 8:
1498   case 16:
1499   case 32:
1500   case 64:
1501     return N;
1502   default:
1503     cerr << "Bits = " << N << '\n';
1504     llvm_unreachable("Unsupported integer width");
1505   }
1506   return 0; // Not reached
1507 }
1508
1509
1510 void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1511   uint64_t TySize = 0;
1512   const Type* Ty = C->getType();
1513   // Print zero initialized constant.
1514   if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
1515     TySize = TD->getTypeAllocSize(C->getType());
1516     Offset += TySize;
1517     Out << "int8 (0) [" << TySize << "]";
1518     return;
1519   }
1520   // Print constant initializer
1521   switch (Ty->getTypeID()) {
1522   case Type::IntegerTyID: {
1523     TySize = TD->getTypeAllocSize(Ty);
1524     const ConstantInt* Int = cast<ConstantInt>(C);
1525     Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1526     break;
1527   }
1528   case Type::FloatTyID:
1529   case Type::DoubleTyID: {
1530     TySize = TD->getTypeAllocSize(Ty);
1531     const ConstantFP* FP = cast<ConstantFP>(C);
1532     if (Ty->getTypeID() == Type::FloatTyID)
1533       Out << "int32 (" << 
1534         (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1535     else
1536       Out << "int64 (" << 
1537         FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1538     break;
1539   }
1540   case Type::ArrayTyID:
1541   case Type::VectorTyID:
1542   case Type::StructTyID:
1543     for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1544       if (I!=0) Out << ",\n";
1545       printStaticConstant(C->getOperand(I),Offset);
1546     }
1547     break;
1548   case Type::PointerTyID:
1549     TySize = TD->getTypeAllocSize(C->getType());
1550     // Initialize with global variable address
1551     if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1552       std::string name = getValueName(G);
1553       Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1554     } else {
1555       // Dynamic initialization
1556       if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1557         InitListPtr->push_back(StaticInitializer(C,Offset));
1558       // Null pointer initialization
1559       if (TySize==4) Out << "int32 (0)";
1560       else if (TySize==8) Out << "int64 (0)";
1561       else llvm_unreachable("Invalid pointer size");
1562     }
1563     break;
1564   default:
1565     cerr << "TypeID = " << Ty->getTypeID() << '\n';
1566     llvm_unreachable("Invalid type in printStaticConstant()");
1567   }
1568   // Increase offset.
1569   Offset += TySize;
1570 }
1571
1572
1573 void MSILWriter::printStaticInitializer(const Constant* C,
1574                                         const std::string& Name) {
1575   switch (C->getType()->getTypeID()) {
1576   case Type::IntegerTyID:
1577   case Type::FloatTyID:
1578   case Type::DoubleTyID: 
1579     Out << getPrimitiveTypeName(C->getType(), false);
1580     break;
1581   case Type::ArrayTyID:
1582   case Type::VectorTyID:
1583   case Type::StructTyID:
1584   case Type::PointerTyID:
1585     Out << getTypeName(C->getType());
1586     break;
1587   default:
1588     cerr << "Type = " << *C << "\n";
1589     llvm_unreachable("Invalid constant type");
1590   }
1591   // Print initializer
1592   std::string label = Name;
1593   label.insert(label.length()-1,"$data");
1594   Out << Name << " at " << label << '\n';
1595   Out << ".data " << label << " = {\n";
1596   uint64_t offset = 0;
1597   printStaticConstant(C,offset);
1598   Out << "\n}\n\n";
1599 }
1600
1601
1602 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1603   const Constant* C = G->getInitializer();
1604   if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1605     InitListPtr = 0;
1606   else
1607     InitListPtr = &StaticInitList[G];
1608   printStaticInitializer(C,getValueName(G));
1609 }
1610
1611
1612 void MSILWriter::printGlobalVariables() {
1613   if (ModulePtr->global_empty()) return;
1614   Module::global_iterator I,E;
1615   for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1616     // Variable definition
1617     Out << ".field static " << (I->isDeclaration() ? "public " :
1618                                                      "private ");
1619     if (I->isDeclaration()) {
1620       Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1621     } else
1622       printVariableDefinition(&*I);
1623   }
1624 }
1625
1626
1627 const char* MSILWriter::getLibraryName(const Function* F) {
1628   return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1629 }
1630
1631
1632 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1633   return getLibraryForSymbol(Mang->getValueName(GV).c_str(), false, 0);
1634 }
1635
1636
1637 const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1638                                            unsigned CallingConv) {
1639   // TODO: Read *.def file with function and libraries definitions.
1640   return "MSVCRT.DLL";  
1641 }
1642
1643
1644 void MSILWriter::printExternals() {
1645   Module::const_iterator I,E;
1646   // Functions.
1647   for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1648     // Skip intrisics
1649     if (I->isIntrinsic()) continue;
1650     if (I->isDeclaration()) {
1651       const Function* F = I; 
1652       std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1653       std::string Sig = 
1654         getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1655       Out << ".method static hidebysig pinvokeimpl(\""
1656           << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1657     }
1658   }
1659   // External variables and static initialization.
1660   Out <<
1661   ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1662   "  native int LoadLibrary(string) preservesig {}\n"
1663   ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1664   "  native int GetProcAddress(native int, string) preservesig {}\n";
1665   Out <<
1666   ".method private static void* $MSIL_Import(string lib,string sym)\n"
1667   " managed cil\n{\n"
1668   "\tldarg\tlib\n"
1669   "\tcall\tnative int LoadLibrary(string)\n"
1670   "\tldarg\tsym\n"
1671   "\tcall\tnative int GetProcAddress(native int,string)\n"
1672   "\tdup\n"
1673   "\tbrtrue\tL_01\n"
1674   "\tldstr\t\"Can no import variable\"\n"
1675   "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1676   "\tthrow\n"
1677   "L_01:\n"
1678   "\tret\n"
1679   "}\n\n"
1680   ".method static private void $MSIL_Init() managed cil\n{\n";
1681   printStaticInitializerList();
1682   // Foreach global variable.
1683   for (Module::global_iterator I = ModulePtr->global_begin(),
1684        E = ModulePtr->global_end(); I!=E; ++I) {
1685     if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1686     // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1687     std::string Label = "not_null$_"+utostr(getUniqID());
1688     std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1689     printSimpleInstruction("ldsflda",Tmp.c_str());
1690     Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1691     Out << "\tldstr\t\"" << Mang->getValueName(&*I) << "\"\n";
1692     printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1693     printIndirectSave(I->getType());
1694   }
1695   printSimpleInstruction("ret");
1696   Out << "}\n\n";
1697 }
1698
1699
1700 //===----------------------------------------------------------------------===//
1701 //                      External Interface declaration
1702 //===----------------------------------------------------------------------===//
1703
1704 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM, raw_ostream &o,
1705                                           CodeGenFileType FileType,
1706                                           CodeGenOpt::Level OptLevel)
1707 {
1708   if (FileType != TargetMachine::AssemblyFile) return true;
1709   MSILWriter* Writer = new MSILWriter(o);
1710   PM.add(createGCLoweringPass());
1711   PM.add(createLowerAllocationsPass(true));
1712   // FIXME: Handle switch trougth native IL instruction "switch"
1713   PM.add(createLowerSwitchPass());
1714   PM.add(createCFGSimplificationPass());
1715   PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1716   PM.add(Writer);
1717   PM.add(createGCInfoDeleter());
1718   return false;
1719 }