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