blob: 2ae1d4fba28d106b33565cabc69006e397c04730 [file] [log] [blame]
Chris Lattner31c2ec32007-05-06 20:31:17 +00001//===-- MSILWriter.cpp - Library for converting LLVM code to MSIL ---------===//
Anton Korobeynikov099883f2007-03-21 21:38:25 +00002//
Bill Wendling85db3a92008-02-26 10:57:23 +00003// The LLVM Compiler Infrastructure
Anton Korobeynikov099883f2007-03-21 21:38:25 +00004//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00007//
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"
Torok Edwinc25e7582009-07-11 20:10:48 +000022#include "llvm/Support/ErrorHandling.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000023#include "llvm/Support/InstVisitor.h"
Anton Korobeynikovf13090c2007-05-06 20:13:33 +000024#include "llvm/Support/MathExtras.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000025#include "llvm/Transforms/Scalar.h"
26#include "llvm/ADT/StringExtras.h"
Gordon Henriksence224772008-01-07 01:30:38 +000027#include "llvm/CodeGen/Passes.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000028
29namespace {
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; }
David Greene71847812009-07-14 20:18:05 +000038 virtual bool addPassesToEmitWholeFile(PassManager &PM,
39 formatted_raw_ostream &Out,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000040 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +000041 CodeGenOpt::Level OptLevel);
Anton Korobeynikov099883f2007-03-21 21:38:25 +000042
43 // This class always works, but shouldn't be the default in most cases.
44 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
45
46 virtual const TargetData *getTargetData() const { return &DataLayout; }
47 };
48}
49
Oscar Fuentes92adc192008-11-15 21:36:30 +000050/// MSILTargetMachineModule - Note that this is used on hosts that
51/// cannot link in a library unless there are references into the
52/// library. In particular, it seems that it is not possible to get
53/// things to work on Win32 without this. Though it is unused, do not
54/// remove it.
55extern "C" int MSILTargetMachineModule;
56int MSILTargetMachineModule = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000057
Dan Gohmanb8cab922008-10-14 20:25:08 +000058static RegisterTarget<MSILTarget> X("msil", "MSIL backend");
Anton Korobeynikov099883f2007-03-21 21:38:25 +000059
Bob Wilsona96751f2009-06-23 23:59:40 +000060// Force static initialization.
61extern "C" void LLVMInitializeMSILTarget() { }
Douglas Gregor1555a232009-06-16 20:12:29 +000062
Anton Korobeynikov099883f2007-03-21 21:38:25 +000063bool MSILModule::runOnModule(Module &M) {
64 ModulePtr = &M;
65 TD = &getAnalysis<TargetData>();
66 bool Changed = false;
67 // Find named types.
68 TypeSymbolTable& Table = M.getTypeSymbolTable();
69 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
70 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
71 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
72 Table.remove(I++);
73 else {
74 std::set<const Type *>::iterator T = Types.find(I->second);
75 if (T==Types.end())
76 Table.remove(I++);
77 else {
78 Types.erase(T);
79 ++I;
80 }
81 }
82 }
83 // Find unnamed types.
84 unsigned RenameCounter = 0;
85 for (std::set<const Type *>::const_iterator I = Types.begin(),
86 E = Types.end(); I!=E; ++I)
87 if (const StructType *STy = dyn_cast<StructType>(*I)) {
88 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
89 ++RenameCounter;
90 Changed = true;
91 }
92 // Pointer for FunctionPass.
93 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
94 return Changed;
95}
96
Devang Patel19974732007-05-03 01:11:54 +000097char MSILModule::ID = 0;
98char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000099
100bool MSILWriter::runOnFunction(Function &F) {
101 if (F.isDeclaration()) return false;
Chris Lattner9062d9a2009-04-17 00:26:12 +0000102
103 // Do not codegen any 'available_externally' functions at all, they have
104 // definitions outside the translation unit.
105 if (F.hasAvailableExternallyLinkage())
106 return false;
107
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000108 LInfo = &getAnalysis<LoopInfo>();
109 printFunction(F);
110 return false;
111}
112
113
114bool MSILWriter::doInitialization(Module &M) {
115 ModulePtr = &M;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000116 Mang = new Mangler(M);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000117 Out << ".assembly extern mscorlib {}\n";
118 Out << ".assembly MSIL {}\n\n";
119 Out << "// External\n";
120 printExternals();
121 Out << "// Declarations\n";
122 printDeclarations(M.getTypeSymbolTable());
123 Out << "// Definitions\n";
124 printGlobalVariables();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000125 Out << "// Startup code\n";
126 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000127 return false;
128}
129
130
131bool MSILWriter::doFinalization(Module &M) {
132 delete Mang;
133 return false;
134}
135
136
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000137void MSILWriter::printModuleStartup() {
138 Out <<
139 ".method static public int32 $MSIL_Startup() {\n"
140 "\t.entrypoint\n"
141 "\t.locals (native int i)\n"
142 "\t.locals (native int argc)\n"
143 "\t.locals (native int ptr)\n"
144 "\t.locals (void* argv)\n"
145 "\t.locals (string[] args)\n"
146 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
147 "\tdup\n"
148 "\tstloc\targs\n"
149 "\tldlen\n"
150 "\tconv.i4\n"
151 "\tdup\n"
152 "\tstloc\targc\n";
153 printPtrLoad(TD->getPointerSize());
154 Out <<
155 "\tmul\n"
156 "\tlocalloc\n"
157 "\tstloc\targv\n"
158 "\tldc.i4.0\n"
159 "\tstloc\ti\n"
160 "L_01:\n"
161 "\tldloc\ti\n"
162 "\tldloc\targc\n"
163 "\tceq\n"
164 "\tbrtrue\tL_02\n"
165 "\tldloc\targs\n"
166 "\tldloc\ti\n"
167 "\tldelem.ref\n"
168 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
169 "StringToHGlobalAnsi(string)\n"
170 "\tstloc\tptr\n"
171 "\tldloc\targv\n"
172 "\tldloc\ti\n";
173 printPtrLoad(TD->getPointerSize());
174 Out <<
175 "\tmul\n"
176 "\tadd\n"
177 "\tldloc\tptr\n"
178 "\tstind.i\n"
179 "\tldloc\ti\n"
180 "\tldc.i4.1\n"
181 "\tadd\n"
182 "\tstloc\ti\n"
183 "\tbr\tL_01\n"
184 "L_02:\n"
185 "\tcall void $MSIL_Init()\n";
186
187 // Call user 'main' function.
188 const Function* F = ModulePtr->getFunction("main");
189 if (!F || F->isDeclaration()) {
190 Out << "\tldc.i4.0\n\tret\n}\n";
191 return;
192 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000193 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000194 std::string Args("");
195 Function::const_arg_iterator Arg1,Arg2;
196
197 switch (F->arg_size()) {
198 case 0:
199 BadSig = false;
200 break;
201 case 1:
202 Arg1 = F->arg_begin();
203 if (Arg1->getType()->isInteger()) {
204 Out << "\tldloc\targc\n";
205 Args = getTypeName(Arg1->getType());
206 BadSig = false;
207 }
208 break;
209 case 2:
210 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
211 if (Arg1->getType()->isInteger() &&
212 Arg2->getType()->getTypeID() == Type::PointerTyID) {
213 Out << "\tldloc\targc\n\tldloc\targv\n";
214 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
215 BadSig = false;
216 }
217 break;
218 default:
219 BadSig = true;
220 }
221
222 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
Anton Korobeynikov7c1c2612008-02-20 11:22:39 +0000223 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000224 Out << "\tldc.i4.0\n";
225 } else {
226 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
227 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
228 if (RetVoid)
229 Out << "\tldc.i4.0\n";
230 else
231 Out << "\tconv.i4\n";
232 }
233 Out << "\tret\n}\n";
234}
235
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000236bool MSILWriter::isZeroValue(const Value* V) {
237 if (const Constant *C = dyn_cast<Constant>(V))
238 return C->isNullValue();
239 return false;
240}
241
242
243std::string MSILWriter::getValueName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000244 std::string Name;
245 if (const GlobalValue *GV = cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000246 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000247 else {
248 unsigned &No = AnonValueNumbers[V];
249 if (No == 0) No = ++NextAnonValueNumber;
250 Name = "tmp" + utostr(No);
251 }
252
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000253 // Name into the quotes allow control and space characters.
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000254 return "'"+Name+"'";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000255}
256
257
258std::string MSILWriter::getLabelName(const std::string& Name) {
259 if (Name.find('.')!=std::string::npos) {
260 std::string Tmp(Name);
261 // Replace unaccepable characters in the label name.
262 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
263 if (*I=='.') *I = '@';
264 return Tmp;
265 }
266 return Name;
267}
268
269
270std::string MSILWriter::getLabelName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000271 std::string Name;
272 if (const GlobalValue *GV = cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000273 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000274 else {
275 unsigned &No = AnonValueNumbers[V];
276 if (No == 0) No = ++NextAnonValueNumber;
277 Name = "tmp" + utostr(No);
278 }
279
280 return getLabelName(Name);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000281}
282
283
284std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
285 switch (CallingConvID) {
286 case CallingConv::C:
287 case CallingConv::Cold:
288 case CallingConv::Fast:
289 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
290 case CallingConv::X86_FastCall:
291 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
292 case CallingConv::X86_StdCall:
293 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
294 default:
295 cerr << "CallingConvID = " << CallingConvID << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000296 llvm_unreachable("Unsupported calling convention");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000297 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000298 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000299}
300
301
302std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
303 std::string Tmp = "";
304 const Type* ElemTy = Ty;
305 assert(Ty->getTypeID()==TyID && "Invalid type passed");
306 // Walk trought array element types.
307 for (;;) {
308 // Multidimensional array.
309 if (ElemTy->getTypeID()==TyID) {
310 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
311 Tmp += utostr(ATy->getNumElements());
312 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
313 Tmp += utostr(VTy->getNumElements());
314 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
315 }
316 // Base element type found.
317 if (ElemTy->getTypeID()!=TyID) break;
318 Tmp += ",";
319 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000320 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000321}
322
323
324std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
325 unsigned NumBits = 0;
326 switch (Ty->getTypeID()) {
327 case Type::VoidTyID:
328 return "void ";
329 case Type::IntegerTyID:
330 NumBits = getBitWidth(Ty);
331 if(NumBits==1)
332 return "bool ";
333 if (!isSigned)
334 return "unsigned int"+utostr(NumBits)+" ";
335 return "int"+utostr(NumBits)+" ";
336 case Type::FloatTyID:
337 return "float32 ";
338 case Type::DoubleTyID:
339 return "float64 ";
340 default:
341 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000342 llvm_unreachable("Invalid primitive type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000343 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000344 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000345}
346
347
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000348std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
349 bool isNested) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000350 if (Ty->isPrimitiveType() || Ty->isInteger())
351 return getPrimitiveTypeName(Ty,isSigned);
352 // FIXME: "OpaqueType" support
353 switch (Ty->getTypeID()) {
354 case Type::PointerTyID:
355 return "void* ";
356 case Type::StructTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000357 if (isNested)
358 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000359 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
360 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000361 if (isNested)
362 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000363 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
364 case Type::VectorTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000365 if (isNested)
366 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000367 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
368 default:
369 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000370 llvm_unreachable("Invalid type in getTypeName()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000371 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000372 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000373}
374
375
376MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
377 // Function argument
378 if (isa<Argument>(V))
379 return ArgumentVT;
380 // Function
381 else if (const Function* F = dyn_cast<Function>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000382 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000383 // Variable
384 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000385 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000386 // Constant
387 else if (isa<Constant>(V))
388 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
389 // Local variable
390 return LocalVT;
391}
392
393
394std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
395 bool isSigned) {
396 unsigned NumBits = 0;
397 switch (Ty->getTypeID()) {
398 // Integer constant, expanding for stack operations.
399 case Type::IntegerTyID:
400 NumBits = getBitWidth(Ty);
401 // Expand integer value to "int32" or "int64".
402 if (Expand) return (NumBits<=32 ? "i4" : "i8");
403 if (NumBits==1) return "i1";
404 return (isSigned ? "i" : "u")+utostr(NumBits/8);
405 // Float constant.
406 case Type::FloatTyID:
407 return "r4";
408 case Type::DoubleTyID:
409 return "r8";
410 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +0000411 return "i"+utostr(TD->getTypeAllocSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000412 default:
413 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000414 llvm_unreachable("Invalid type in TypeToPostfix()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000415 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000416 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000417}
418
419
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000420void MSILWriter::printConvToPtr() {
421 switch (ModulePtr->getPointerSize()) {
422 case Module::Pointer32:
423 printSimpleInstruction("conv.u4");
424 break;
425 case Module::Pointer64:
426 printSimpleInstruction("conv.u8");
427 break;
428 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000429 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000430 }
431}
432
433
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000434void MSILWriter::printPtrLoad(uint64_t N) {
435 switch (ModulePtr->getPointerSize()) {
436 case Module::Pointer32:
437 printSimpleInstruction("ldc.i4",utostr(N).c_str());
438 // FIXME: Need overflow test?
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000439 if (!isUInt32(N)) {
440 cerr << "Value = " << utostr(N) << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000441 llvm_unreachable("32-bit pointer overflowed");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000442 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000443 break;
444 case Module::Pointer64:
445 printSimpleInstruction("ldc.i8",utostr(N).c_str());
446 break;
447 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000448 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000449 }
450}
451
452
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000453void MSILWriter::printValuePtrLoad(const Value* V) {
454 printValueLoad(V);
455 printConvToPtr();
456}
457
458
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000459void MSILWriter::printConstLoad(const Constant* C) {
460 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
461 // Integer constant
462 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
463 if (CInt->isMinValue(true))
464 Out << CInt->getSExtValue();
465 else
466 Out << CInt->getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000467 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000468 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000469 uint64_t X;
470 unsigned Size;
471 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000472 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000473 Size = 4;
474 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000475 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000476 Size = 8;
477 }
478 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
479 } else if (isa<UndefValue>(C)) {
480 // Undefined constant value = NULL.
481 printPtrLoad(0);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000482 } else {
483 cerr << "Constant = " << *C << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000484 llvm_unreachable("Invalid constant value");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000485 }
486 Out << '\n';
487}
488
489
490void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000491 MSILWriter::ValueType Location = getValueLocation(V);
492 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000493 // Global variable or function address.
494 case GlobalVT:
495 case InternalVT:
496 if (const Function* F = dyn_cast<Function>(V)) {
497 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
498 printSimpleInstruction("ldftn",
499 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
500 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000501 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000502 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000503 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
504 Tmp = "void* "+getValueName(V);
505 printSimpleInstruction("ldsfld",Tmp.c_str());
506 } else {
507 Tmp = getTypeName(ElemTy)+getValueName(V);
508 printSimpleInstruction("ldsflda",Tmp.c_str());
509 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000510 }
511 break;
512 // Function argument.
513 case ArgumentVT:
514 printSimpleInstruction("ldarg",getValueName(V).c_str());
515 break;
516 // Local function variable.
517 case LocalVT:
518 printSimpleInstruction("ldloc",getValueName(V).c_str());
519 break;
520 // Constant value.
521 case ConstVT:
522 if (isa<ConstantPointerNull>(V))
523 printPtrLoad(0);
524 else
525 printConstLoad(cast<Constant>(V));
526 break;
527 // Constant expression.
528 case ConstExprVT:
529 printConstantExpr(cast<ConstantExpr>(V));
530 break;
531 default:
532 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000533 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000534 }
535}
536
537
538void MSILWriter::printValueSave(const Value* V) {
539 switch (getValueLocation(V)) {
540 case ArgumentVT:
541 printSimpleInstruction("starg",getValueName(V).c_str());
542 break;
543 case LocalVT:
544 printSimpleInstruction("stloc",getValueName(V).c_str());
545 break;
546 default:
547 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000548 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000549 }
550}
551
552
553void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
554 const Value* Right) {
555 printValueLoad(Left);
556 printValueLoad(Right);
557 Out << '\t' << Name << '\n';
558}
559
560
561void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
562 if(Operand)
563 Out << '\t' << Inst << '\t' << Operand << '\n';
564 else
565 Out << '\t' << Inst << '\n';
566}
567
568
569void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
570 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
571 isa<PHINode>(I); ++I) {
572 const PHINode* Phi = cast<PHINode>(I);
573 const Value* Val = Phi->getIncomingValueForBlock(Src);
574 if (isa<UndefValue>(Val)) continue;
575 printValueLoad(Val);
576 printValueSave(Phi);
577 }
578}
579
580
581void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
582 const BasicBlock* TrueBB,
583 const BasicBlock* FalseBB) {
584 if (TrueBB==FalseBB) {
585 // "TrueBB" and "FalseBB" destination equals
586 printPHICopy(CurrBB,TrueBB);
587 printSimpleInstruction("pop");
588 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
589 } else if (FalseBB==NULL) {
590 // If "FalseBB" not used the jump have condition
591 printPHICopy(CurrBB,TrueBB);
592 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
593 } else if (TrueBB==NULL) {
594 // If "TrueBB" not used the jump is unconditional
595 printPHICopy(CurrBB,FalseBB);
596 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
597 } else {
598 // Copy PHI instructions for each block
599 std::string TmpLabel;
600 // Print PHI instructions for "TrueBB"
601 if (isa<PHINode>(TrueBB->begin())) {
602 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
603 printSimpleInstruction("brtrue",TmpLabel.c_str());
604 } else {
605 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
606 }
607 // Print PHI instructions for "FalseBB"
608 if (isa<PHINode>(FalseBB->begin())) {
609 printPHICopy(CurrBB,FalseBB);
610 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
611 } else {
612 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
613 }
614 if (isa<PHINode>(TrueBB->begin())) {
615 // Handle "TrueBB" PHI Copy
616 Out << TmpLabel << ":\n";
617 printPHICopy(CurrBB,TrueBB);
618 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
619 }
620 }
621}
622
623
624void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
625 if (Inst->isUnconditional()) {
626 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
627 } else {
628 printValueLoad(Inst->getCondition());
629 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
630 Inst->getSuccessor(1));
631 }
632}
633
634
635void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
636 const Value* VFalse) {
637 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
638 printValueLoad(VTrue);
639 printValueLoad(Cond);
640 printSimpleInstruction("brtrue",TmpLabel.c_str());
641 printSimpleInstruction("pop");
642 printValueLoad(VFalse);
643 Out << TmpLabel << ":\n";
644}
645
646
647void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000648 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000649 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000650 if (const PointerType* P = dyn_cast<PointerType>(Ty))
651 Ty = P->getElementType();
652 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000653 printSimpleInstruction(Tmp.c_str());
654}
655
656
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000657void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000658 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000659 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000660 printIndirectSave(Val->getType());
661}
662
663
664void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000665 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000666 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000667 if (*postfix.begin()=='u') *postfix.begin() = 'i';
668 postfix = "stind."+postfix;
669 printSimpleInstruction(postfix.c_str());
670}
671
672
673void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000674 const Type* Ty, const Type* SrcTy) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000675 std::string Tmp("");
676 printValueLoad(V);
677 switch (Op) {
678 // Signed
679 case Instruction::SExt:
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000680 // If sign extending int, convert first from unsigned to signed
681 // with the same bit size - because otherwise we will loose the sign.
682 if (SrcTy) {
683 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
684 printSimpleInstruction(Tmp.c_str());
685 }
Bill Wendling5f544502009-07-14 18:30:04 +0000686 // FALLTHROUGH
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000687 case Instruction::SIToFP:
688 case Instruction::FPToSI:
689 Tmp = "conv."+getTypePostfix(Ty,false,true);
690 printSimpleInstruction(Tmp.c_str());
691 break;
692 // Unsigned
693 case Instruction::FPTrunc:
694 case Instruction::FPExt:
695 case Instruction::UIToFP:
696 case Instruction::Trunc:
697 case Instruction::ZExt:
698 case Instruction::FPToUI:
699 case Instruction::PtrToInt:
700 case Instruction::IntToPtr:
701 Tmp = "conv."+getTypePostfix(Ty,false);
702 printSimpleInstruction(Tmp.c_str());
703 break;
704 // Do nothing
705 case Instruction::BitCast:
706 // FIXME: meaning that ld*/st* instruction do not change data format.
707 break;
708 default:
709 cerr << "Opcode = " << Op << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000710 llvm_unreachable("Invalid conversion instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000711 }
712}
713
714
715void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
716 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000717 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000718 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000719 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000720 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000721 for (; I!=E; ++I){
722 Size = 0;
723 const Value* IndexValue = I.getOperand();
724 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
725 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
726 // Offset is the sum of all previous structure fields.
727 for (uint64_t F = 0; F<FieldIndex; ++F)
Duncan Sands777d2302009-05-09 07:06:46 +0000728 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000729 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000730 printSimpleInstruction("add");
731 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000732 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000733 Size = TD->getTypeAllocSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000734 } else {
Duncan Sands777d2302009-05-09 07:06:46 +0000735 Size = TD->getTypeAllocSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000736 }
737 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000738 if (!isZeroValue(IndexValue)) {
739 // Constant optimization.
740 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
741 if (C->getValue().isNegative()) {
742 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
743 printSimpleInstruction("sub");
744 continue;
745 } else
746 printPtrLoad(C->getZExtValue()*Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000747 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000748 printPtrLoad(Size);
749 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000750 printSimpleInstruction("mul");
751 }
752 printSimpleInstruction("add");
753 }
754 }
755}
756
757
758std::string MSILWriter::getCallSignature(const FunctionType* Ty,
759 const Instruction* Inst,
760 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000761 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000762 if (Ty->isVarArg()) Tmp += "vararg ";
763 // Name and return type.
764 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
765 // Function argument type list.
766 unsigned NumParams = Ty->getNumParams();
767 for (unsigned I = 0; I!=NumParams; ++I) {
768 if (I!=0) Tmp += ",";
769 Tmp += getTypeName(Ty->getParamType(I));
770 }
771 // CLR needs to know the exact amount of parameters received by vararg
772 // function, because caller cleans the stack.
773 if (Ty->isVarArg() && Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000774 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000775 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
776 // Print variable argument types.
777 unsigned NumOperands = Inst->getNumOperands()-Org;
778 if (NumParams<NumOperands) {
779 if (NumParams!=0) Tmp += ", ";
780 Tmp += "... , ";
781 for (unsigned J = NumParams; J!=NumOperands; ++J) {
782 if (J!=NumParams) Tmp += ", ";
783 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
784 }
785 }
786 }
787 return Tmp+")";
788}
789
790
791void MSILWriter::printFunctionCall(const Value* FnVal,
792 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000793 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000794 std::string Name = "";
795 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
796 Name = getConvModopt(Call->getCallingConv());
797 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
798 Name = getConvModopt(Invoke->getCallingConv());
799 else {
800 cerr << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000801 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000802 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000803 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000804 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000805 Name += getValueName(F);
806 printSimpleInstruction("call",
807 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
808 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000809 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000810 const PointerType* PTy = cast<PointerType>(FnVal->getType());
811 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000812 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000813 printValueLoad(FnVal);
814 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
815 }
816}
817
818
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000819void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
820 std::string Name;
821 switch (Inst->getIntrinsicID()) {
822 case Intrinsic::vastart:
823 Name = getValueName(Inst->getOperand(1));
824 Name.insert(Name.length()-1,"$valist");
825 // Obtain the argument handle.
826 printSimpleInstruction("ldloca",Name.c_str());
827 printSimpleInstruction("arglist");
828 printSimpleInstruction("call",
829 "instance void [mscorlib]System.ArgIterator::.ctor"
830 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
831 // Save as pointer type "void*"
832 printValueLoad(Inst->getOperand(1));
833 printSimpleInstruction("ldloca",Name.c_str());
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000834 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000835 break;
836 case Intrinsic::vaend:
837 // Close argument list handle.
838 printIndirectLoad(Inst->getOperand(1));
839 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
840 break;
841 case Intrinsic::vacopy:
842 // Copy "ArgIterator" valuetype.
843 printIndirectLoad(Inst->getOperand(1));
844 printIndirectLoad(Inst->getOperand(2));
845 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
846 break;
847 default:
848 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000849 llvm_unreachable("Invalid intrinsic function");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000850 }
851}
852
853
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000854void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000855 if (isa<IntrinsicInst>(Inst)) {
856 // Handle intrinsic function.
857 printIntrinsicCall(cast<IntrinsicInst>(Inst));
858 } else {
859 // Load arguments to stack and call function.
860 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
861 printValueLoad(Inst->getOperand(I));
862 printFunctionCall(Inst->getOperand(0),Inst);
863 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000864}
865
866
867void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
868 const Value* Right) {
869 switch (Predicate) {
870 case ICmpInst::ICMP_EQ:
871 printBinaryInstruction("ceq",Left,Right);
872 break;
873 case ICmpInst::ICMP_NE:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000874 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000875 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000876 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000877 printSimpleInstruction("not");
878 break;
879 case ICmpInst::ICMP_ULE:
880 case ICmpInst::ICMP_SLE:
881 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
882 printBinaryInstruction("ceq",Left,Right);
883 if (Predicate==ICmpInst::ICMP_ULE)
884 printBinaryInstruction("clt.un",Left,Right);
885 else
886 printBinaryInstruction("clt",Left,Right);
887 printSimpleInstruction("or");
888 break;
889 case ICmpInst::ICMP_UGE:
890 case ICmpInst::ICMP_SGE:
891 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
892 printBinaryInstruction("ceq",Left,Right);
893 if (Predicate==ICmpInst::ICMP_UGE)
894 printBinaryInstruction("cgt.un",Left,Right);
895 else
896 printBinaryInstruction("cgt",Left,Right);
897 printSimpleInstruction("or");
898 break;
899 case ICmpInst::ICMP_ULT:
900 printBinaryInstruction("clt.un",Left,Right);
901 break;
902 case ICmpInst::ICMP_SLT:
903 printBinaryInstruction("clt",Left,Right);
904 break;
905 case ICmpInst::ICMP_UGT:
906 printBinaryInstruction("cgt.un",Left,Right);
Anton Korobeynikove9fd67e2009-07-14 09:52:47 +0000907 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000908 case ICmpInst::ICMP_SGT:
909 printBinaryInstruction("cgt",Left,Right);
910 break;
911 default:
912 cerr << "Predicate = " << Predicate << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000913 llvm_unreachable("Invalid icmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000914 }
915}
916
917
918void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
919 const Value* Right) {
920 // FIXME: Correct comparison
921 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
922 switch (Predicate) {
923 case FCmpInst::FCMP_UGT:
924 // X > Y || llvm_fcmp_uno(X, Y)
925 printBinaryInstruction("cgt",Left,Right);
926 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
927 printSimpleInstruction("or");
928 break;
929 case FCmpInst::FCMP_OGT:
930 // X > Y
931 printBinaryInstruction("cgt",Left,Right);
932 break;
933 case FCmpInst::FCMP_UGE:
934 // X >= Y || llvm_fcmp_uno(X, Y)
935 printBinaryInstruction("ceq",Left,Right);
936 printBinaryInstruction("cgt",Left,Right);
937 printSimpleInstruction("or");
938 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
939 printSimpleInstruction("or");
940 break;
941 case FCmpInst::FCMP_OGE:
942 // X >= Y
943 printBinaryInstruction("ceq",Left,Right);
944 printBinaryInstruction("cgt",Left,Right);
945 printSimpleInstruction("or");
946 break;
947 case FCmpInst::FCMP_ULT:
948 // X < Y || llvm_fcmp_uno(X, Y)
949 printBinaryInstruction("clt",Left,Right);
950 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
951 printSimpleInstruction("or");
952 break;
953 case FCmpInst::FCMP_OLT:
954 // X < Y
955 printBinaryInstruction("clt",Left,Right);
956 break;
957 case FCmpInst::FCMP_ULE:
958 // X <= Y || llvm_fcmp_uno(X, Y)
959 printBinaryInstruction("ceq",Left,Right);
960 printBinaryInstruction("clt",Left,Right);
961 printSimpleInstruction("or");
962 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
963 printSimpleInstruction("or");
964 break;
965 case FCmpInst::FCMP_OLE:
966 // X <= Y
967 printBinaryInstruction("ceq",Left,Right);
968 printBinaryInstruction("clt",Left,Right);
969 printSimpleInstruction("or");
970 break;
971 case FCmpInst::FCMP_UEQ:
972 // X == Y || llvm_fcmp_uno(X, Y)
973 printBinaryInstruction("ceq",Left,Right);
974 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
975 printSimpleInstruction("or");
976 break;
977 case FCmpInst::FCMP_OEQ:
978 // X == Y
979 printBinaryInstruction("ceq",Left,Right);
980 break;
981 case FCmpInst::FCMP_UNE:
982 // X != Y
983 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000984 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000985 printSimpleInstruction("not");
986 break;
987 case FCmpInst::FCMP_ONE:
988 // X != Y && llvm_fcmp_ord(X, Y)
989 printBinaryInstruction("ceq",Left,Right);
990 printSimpleInstruction("not");
991 break;
992 case FCmpInst::FCMP_ORD:
993 // return X == X && Y == Y
994 printBinaryInstruction("ceq",Left,Left);
995 printBinaryInstruction("ceq",Right,Right);
996 printSimpleInstruction("or");
997 break;
998 case FCmpInst::FCMP_UNO:
999 // X != X || Y != Y
1000 printBinaryInstruction("ceq",Left,Left);
1001 printSimpleInstruction("not");
1002 printBinaryInstruction("ceq",Right,Right);
1003 printSimpleInstruction("not");
1004 printSimpleInstruction("or");
1005 break;
1006 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001007 llvm_unreachable("Illegal FCmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001008 }
1009}
1010
1011
1012void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1013 std::string Label = "leave$normal_"+utostr(getUniqID());
1014 Out << ".try {\n";
1015 // Load arguments
1016 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1017 printValueLoad(Inst->getOperand(I));
1018 // Print call instruction
1019 printFunctionCall(Inst->getOperand(0),Inst);
1020 // Save function result and leave "try" block
1021 printValueSave(Inst);
1022 printSimpleInstruction("leave",Label.c_str());
1023 Out << "}\n";
1024 Out << "catch [mscorlib]System.Exception {\n";
1025 // Redirect to unwind block
1026 printSimpleInstruction("pop");
1027 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1028 Out << "}\n" << Label << ":\n";
1029 // Redirect to continue block
1030 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1031}
1032
1033
1034void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1035 // FIXME: Emulate with IL "switch" instruction
1036 // Emulate = if () else if () else if () else ...
1037 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1038 printValueLoad(Inst->getCondition());
1039 printValueLoad(Inst->getCaseValue(I));
1040 printSimpleInstruction("ceq");
1041 // Condition jump to successor block
1042 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1043 }
1044 // Jump to default block
1045 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1046}
1047
1048
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001049void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1050 printIndirectLoad(Inst->getOperand(0));
1051 printSimpleInstruction("call",
1052 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1053 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001054 std::string Name =
1055 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001056 printSimpleInstruction(Name.c_str());
1057}
1058
1059
1060void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
Duncan Sands777d2302009-05-09 07:06:46 +00001061 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001062 // Constant optimization.
1063 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1064 printPtrLoad(CInt->getZExtValue()*Size);
1065 } else {
1066 printPtrLoad(Size);
1067 printValueLoad(Inst->getOperand(0));
1068 printSimpleInstruction("mul");
1069 }
1070 printSimpleInstruction("localloc");
1071}
1072
1073
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001074void MSILWriter::printInstruction(const Instruction* Inst) {
1075 const Value *Left = 0, *Right = 0;
1076 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1077 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1078 // Print instruction
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001079 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001080 switch (Inst->getOpcode()) {
1081 // Terminator
1082 case Instruction::Ret:
1083 if (Inst->getNumOperands()) {
1084 printValueLoad(Left);
1085 printSimpleInstruction("ret");
1086 } else
1087 printSimpleInstruction("ret");
1088 break;
1089 case Instruction::Br:
1090 printBranchInstruction(cast<BranchInst>(Inst));
1091 break;
1092 // Binary
1093 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001094 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001095 printBinaryInstruction("add",Left,Right);
1096 break;
1097 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001098 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001099 printBinaryInstruction("sub",Left,Right);
1100 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001101 case Instruction::Mul:
1102 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001103 printBinaryInstruction("mul",Left,Right);
1104 break;
1105 case Instruction::UDiv:
1106 printBinaryInstruction("div.un",Left,Right);
1107 break;
1108 case Instruction::SDiv:
1109 case Instruction::FDiv:
1110 printBinaryInstruction("div",Left,Right);
1111 break;
1112 case Instruction::URem:
1113 printBinaryInstruction("rem.un",Left,Right);
1114 break;
1115 case Instruction::SRem:
1116 case Instruction::FRem:
1117 printBinaryInstruction("rem",Left,Right);
1118 break;
1119 // Binary Condition
1120 case Instruction::ICmp:
1121 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1122 break;
1123 case Instruction::FCmp:
1124 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1125 break;
1126 // Bitwise Binary
1127 case Instruction::And:
1128 printBinaryInstruction("and",Left,Right);
1129 break;
1130 case Instruction::Or:
1131 printBinaryInstruction("or",Left,Right);
1132 break;
1133 case Instruction::Xor:
1134 printBinaryInstruction("xor",Left,Right);
1135 break;
1136 case Instruction::Shl:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001137 printValueLoad(Left);
1138 printValueLoad(Right);
1139 printSimpleInstruction("conv.i4");
1140 printSimpleInstruction("shl");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001141 break;
1142 case Instruction::LShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001143 printValueLoad(Left);
1144 printValueLoad(Right);
1145 printSimpleInstruction("conv.i4");
1146 printSimpleInstruction("shr.un");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001147 break;
1148 case Instruction::AShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001149 printValueLoad(Left);
1150 printValueLoad(Right);
1151 printSimpleInstruction("conv.i4");
1152 printSimpleInstruction("shr");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001153 break;
1154 case Instruction::Select:
1155 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1156 break;
1157 case Instruction::Load:
1158 printIndirectLoad(Inst->getOperand(0));
1159 break;
1160 case Instruction::Store:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001161 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001162 break;
Anton Korobeynikov94ac0342009-07-14 09:53:14 +00001163 case Instruction::SExt:
1164 printCastInstruction(Inst->getOpcode(),Left,
1165 cast<CastInst>(Inst)->getDestTy(),
1166 cast<CastInst>(Inst)->getSrcTy());
1167 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001168 case Instruction::Trunc:
1169 case Instruction::ZExt:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001170 case Instruction::FPTrunc:
1171 case Instruction::FPExt:
1172 case Instruction::UIToFP:
1173 case Instruction::SIToFP:
1174 case Instruction::FPToUI:
1175 case Instruction::FPToSI:
1176 case Instruction::PtrToInt:
1177 case Instruction::IntToPtr:
1178 case Instruction::BitCast:
1179 printCastInstruction(Inst->getOpcode(),Left,
1180 cast<CastInst>(Inst)->getDestTy());
1181 break;
1182 case Instruction::GetElementPtr:
1183 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1184 gep_type_end(Inst));
1185 break;
1186 case Instruction::Call:
1187 printCallInstruction(cast<CallInst>(Inst));
1188 break;
1189 case Instruction::Invoke:
1190 printInvokeInstruction(cast<InvokeInst>(Inst));
1191 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001192 case Instruction::Unwind:
1193 printSimpleInstruction("newobj",
1194 "instance void [mscorlib]System.Exception::.ctor()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001195 printSimpleInstruction("throw");
1196 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001197 case Instruction::Switch:
1198 printSwitchInstruction(cast<SwitchInst>(Inst));
1199 break;
1200 case Instruction::Alloca:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001201 printAllocaInstruction(cast<AllocaInst>(Inst));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001202 break;
1203 case Instruction::Malloc:
Torok Edwinc23197a2009-07-14 16:55:14 +00001204 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001205 break;
1206 case Instruction::Free:
Torok Edwinc23197a2009-07-14 16:55:14 +00001207 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001208 break;
1209 case Instruction::Unreachable:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001210 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1211 printSimpleInstruction("newobj",
1212 "instance void [mscorlib]System.Exception::.ctor(string)");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001213 printSimpleInstruction("throw");
1214 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001215 case Instruction::VAArg:
1216 printVAArgInstruction(cast<VAArgInst>(Inst));
1217 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001218 default:
1219 cerr << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001220 llvm_unreachable("Unsupported instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001221 }
1222}
1223
1224
1225void MSILWriter::printLoop(const Loop* L) {
1226 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1227 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1228 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1229 BasicBlock* BB = blocks[I];
1230 Loop* BBLoop = LInfo->getLoopFor(BB);
1231 if (BBLoop == L)
1232 printBasicBlock(BB);
1233 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1234 printLoop(BBLoop);
1235 }
1236 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1237}
1238
1239
1240void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1241 Out << getLabelName(BB) << ":\n";
1242 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1243 const Instruction* Inst = I;
1244 // Comment llvm original instruction
Owen Andersoncb371882008-08-21 00:14:44 +00001245 // Out << "\n//" << *Inst << "\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001246 // Do not handle PHI instruction in current block
1247 if (Inst->getOpcode()==Instruction::PHI) continue;
1248 // Print instruction
1249 printInstruction(Inst);
1250 // Save result
1251 if (Inst->getType()!=Type::VoidTy) {
1252 // Do not save value after invoke, it done in "try" block
1253 if (Inst->getOpcode()==Instruction::Invoke) continue;
1254 printValueSave(Inst);
1255 }
1256 }
1257}
1258
1259
1260void MSILWriter::printLocalVariables(const Function& F) {
1261 std::string Name;
1262 const Type* Ty = NULL;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001263 std::set<const Value*> Printed;
1264 const Value* VaList = NULL;
1265 unsigned StackDepth = 8;
1266 // Find local variables
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001267 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001268 if (I->getOpcode()==Instruction::Call ||
1269 I->getOpcode()==Instruction::Invoke) {
1270 // Test stack depth.
1271 if (StackDepth<I->getNumOperands())
1272 StackDepth = I->getNumOperands();
1273 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001274 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1275 if (AI && !isa<GlobalVariable>(AI)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001276 // Local variable allocation.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001277 Ty = PointerType::getUnqual(AI->getAllocatedType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001278 Name = getValueName(AI);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001279 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001280 } else if (I->getType()!=Type::VoidTy) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001281 // Operation result.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001282 Ty = I->getType();
1283 Name = getValueName(&*I);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001284 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1285 }
1286 // Test on 'va_list' variable
1287 bool isVaList = false;
1288 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1289 // "va_list" as "va_arg" instruction operand.
1290 isVaList = true;
1291 VaList = VaInst->getOperand(0);
1292 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1293 // "va_list" as intrinsic function operand.
1294 switch (Inst->getIntrinsicID()) {
1295 case Intrinsic::vastart:
1296 case Intrinsic::vaend:
1297 case Intrinsic::vacopy:
1298 isVaList = true;
1299 VaList = Inst->getOperand(1);
1300 break;
1301 default:
1302 isVaList = false;
1303 }
1304 }
1305 // Print "va_list" variable.
1306 if (isVaList && Printed.insert(VaList).second) {
1307 Name = getValueName(VaList);
1308 Name.insert(Name.length()-1,"$valist");
1309 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1310 << Name << ")\n";
1311 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001312 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001313 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001314}
1315
1316
1317void MSILWriter::printFunctionBody(const Function& F) {
1318 // Print body
1319 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1320 if (Loop *L = LInfo->getLoopFor(I)) {
1321 if (L->getHeader()==I && L->getParentLoop()==0)
1322 printLoop(L);
1323 } else {
1324 printBasicBlock(I);
1325 }
1326 }
1327}
1328
1329
1330void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1331 const Value *left = 0, *right = 0;
1332 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1333 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1334 // Print instruction
1335 switch (CE->getOpcode()) {
1336 case Instruction::Trunc:
1337 case Instruction::ZExt:
1338 case Instruction::SExt:
1339 case Instruction::FPTrunc:
1340 case Instruction::FPExt:
1341 case Instruction::UIToFP:
1342 case Instruction::SIToFP:
1343 case Instruction::FPToUI:
1344 case Instruction::FPToSI:
1345 case Instruction::PtrToInt:
1346 case Instruction::IntToPtr:
1347 case Instruction::BitCast:
1348 printCastInstruction(CE->getOpcode(),left,CE->getType());
1349 break;
1350 case Instruction::GetElementPtr:
1351 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1352 break;
1353 case Instruction::ICmp:
1354 printICmpInstruction(CE->getPredicate(),left,right);
1355 break;
1356 case Instruction::FCmp:
1357 printFCmpInstruction(CE->getPredicate(),left,right);
1358 break;
1359 case Instruction::Select:
1360 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1361 break;
1362 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001363 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001364 printBinaryInstruction("add",left,right);
1365 break;
1366 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001367 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001368 printBinaryInstruction("sub",left,right);
1369 break;
1370 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001371 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001372 printBinaryInstruction("mul",left,right);
1373 break;
1374 case Instruction::UDiv:
1375 printBinaryInstruction("div.un",left,right);
1376 break;
1377 case Instruction::SDiv:
1378 case Instruction::FDiv:
1379 printBinaryInstruction("div",left,right);
1380 break;
1381 case Instruction::URem:
1382 printBinaryInstruction("rem.un",left,right);
1383 break;
1384 case Instruction::SRem:
1385 case Instruction::FRem:
1386 printBinaryInstruction("rem",left,right);
1387 break;
1388 case Instruction::And:
1389 printBinaryInstruction("and",left,right);
1390 break;
1391 case Instruction::Or:
1392 printBinaryInstruction("or",left,right);
1393 break;
1394 case Instruction::Xor:
1395 printBinaryInstruction("xor",left,right);
1396 break;
1397 case Instruction::Shl:
1398 printBinaryInstruction("shl",left,right);
1399 break;
1400 case Instruction::LShr:
1401 printBinaryInstruction("shr.un",left,right);
1402 break;
1403 case Instruction::AShr:
1404 printBinaryInstruction("shr",left,right);
1405 break;
1406 default:
1407 cerr << "Expression = " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001408 llvm_unreachable("Invalid constant expression");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001409 }
1410}
1411
1412
1413void MSILWriter::printStaticInitializerList() {
1414 // List of global variables with uninitialized fields.
1415 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1416 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1417 ++VarI) {
1418 const std::vector<StaticInitializer>& InitList = VarI->second;
1419 if (InitList.empty()) continue;
1420 // For each uninitialized field.
1421 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1422 E = InitList.end(); I!=E; ++I) {
1423 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
Owen Andersoncb371882008-08-21 00:14:44 +00001424 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1425 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001426 // Load variable address
1427 printValueLoad(VarI->first);
1428 // Add offset
1429 if (I->offset!=0) {
1430 printPtrLoad(I->offset);
1431 printSimpleInstruction("add");
1432 }
1433 // Load value
1434 printConstantExpr(CE);
1435 // Save result at offset
1436 std::string postfix = getTypePostfix(CE->getType(),true);
1437 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1438 postfix = "stind."+postfix;
1439 printSimpleInstruction(postfix.c_str());
1440 } else {
1441 cerr << "Constant = " << *I->constant << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001442 llvm_unreachable("Invalid static initializer");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001443 }
1444 }
1445 }
1446}
1447
1448
1449void MSILWriter::printFunction(const Function& F) {
Devang Patel05988662008-09-25 21:00:45 +00001450 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001451 Out << "\n.method static ";
Rafael Espindolabb46f522009-01-15 20:18:42 +00001452 Out << (F.hasLocalLinkage() ? "private " : "public ");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001453 if (F.isVarArg()) Out << "vararg ";
1454 Out << getTypeName(F.getReturnType(),isSigned) <<
1455 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1456 // Arguments
1457 Out << "\t(";
1458 unsigned ArgIdx = 1;
1459 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1460 ++I, ++ArgIdx) {
Devang Patel05988662008-09-25 21:00:45 +00001461 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001462 if (I!=F.arg_begin()) Out << ", ";
1463 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1464 }
1465 Out << ") cil managed\n";
1466 // Body
1467 Out << "{\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001468 printLocalVariables(F);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001469 printFunctionBody(F);
1470 Out << "}\n";
1471}
1472
1473
1474void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1475 std::string Name;
1476 std::set<const Type*> Printed;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001477 for (std::set<const Type*>::const_iterator
1478 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1479 const Type* Ty = *UI;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001480 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1481 Name = getTypeName(Ty, false, true);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001482 // Type with no need to declare.
1483 else continue;
1484 // Print not duplicated type
1485 if (Printed.insert(Ty).second) {
1486 Out << ".class value explicit ansi sealed '" << Name << "'";
Duncan Sands777d2302009-05-09 07:06:46 +00001487 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001488 Out << " }\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001489 }
1490 }
1491}
1492
1493
1494unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1495 unsigned int N = Ty->getPrimitiveSizeInBits();
1496 assert(N!=0 && "Invalid type in getBitWidth()");
1497 switch (N) {
1498 case 1:
1499 case 8:
1500 case 16:
1501 case 32:
1502 case 64:
1503 return N;
1504 default:
1505 cerr << "Bits = " << N << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001506 llvm_unreachable("Unsupported integer width");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001507 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001508 return 0; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001509}
1510
1511
1512void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1513 uint64_t TySize = 0;
1514 const Type* Ty = C->getType();
1515 // Print zero initialized constant.
1516 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
Duncan Sands777d2302009-05-09 07:06:46 +00001517 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001518 Offset += TySize;
1519 Out << "int8 (0) [" << TySize << "]";
1520 return;
1521 }
1522 // Print constant initializer
1523 switch (Ty->getTypeID()) {
1524 case Type::IntegerTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001525 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001526 const ConstantInt* Int = cast<ConstantInt>(C);
1527 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1528 break;
1529 }
1530 case Type::FloatTyID:
1531 case Type::DoubleTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001532 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001533 const ConstantFP* FP = cast<ConstantFP>(C);
1534 if (Ty->getTypeID() == Type::FloatTyID)
Dale Johannesen43421b32007-09-06 18:13:44 +00001535 Out << "int32 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001536 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001537 else
Dale Johannesen43421b32007-09-06 18:13:44 +00001538 Out << "int64 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001539 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001540 break;
1541 }
1542 case Type::ArrayTyID:
1543 case Type::VectorTyID:
1544 case Type::StructTyID:
1545 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1546 if (I!=0) Out << ",\n";
1547 printStaticConstant(C->getOperand(I),Offset);
1548 }
1549 break;
1550 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +00001551 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001552 // Initialize with global variable address
1553 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1554 std::string name = getValueName(G);
1555 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1556 } else {
1557 // Dynamic initialization
1558 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1559 InitListPtr->push_back(StaticInitializer(C,Offset));
1560 // Null pointer initialization
1561 if (TySize==4) Out << "int32 (0)";
1562 else if (TySize==8) Out << "int64 (0)";
Torok Edwinc23197a2009-07-14 16:55:14 +00001563 else llvm_unreachable("Invalid pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001564 }
1565 break;
1566 default:
1567 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001568 llvm_unreachable("Invalid type in printStaticConstant()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001569 }
1570 // Increase offset.
1571 Offset += TySize;
1572}
1573
1574
1575void MSILWriter::printStaticInitializer(const Constant* C,
1576 const std::string& Name) {
1577 switch (C->getType()->getTypeID()) {
1578 case Type::IntegerTyID:
1579 case Type::FloatTyID:
1580 case Type::DoubleTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001581 Out << getPrimitiveTypeName(C->getType(), false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001582 break;
1583 case Type::ArrayTyID:
1584 case Type::VectorTyID:
1585 case Type::StructTyID:
1586 case Type::PointerTyID:
1587 Out << getTypeName(C->getType());
1588 break;
1589 default:
1590 cerr << "Type = " << *C << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001591 llvm_unreachable("Invalid constant type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001592 }
1593 // Print initializer
1594 std::string label = Name;
1595 label.insert(label.length()-1,"$data");
1596 Out << Name << " at " << label << '\n';
1597 Out << ".data " << label << " = {\n";
1598 uint64_t offset = 0;
1599 printStaticConstant(C,offset);
1600 Out << "\n}\n\n";
1601}
1602
1603
1604void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1605 const Constant* C = G->getInitializer();
1606 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1607 InitListPtr = 0;
1608 else
1609 InitListPtr = &StaticInitList[G];
1610 printStaticInitializer(C,getValueName(G));
1611}
1612
1613
1614void MSILWriter::printGlobalVariables() {
1615 if (ModulePtr->global_empty()) return;
1616 Module::global_iterator I,E;
1617 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1618 // Variable definition
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001619 Out << ".field static " << (I->isDeclaration() ? "public " :
1620 "private ");
1621 if (I->isDeclaration()) {
1622 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1623 } else
1624 printVariableDefinition(&*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001625 }
1626}
1627
1628
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001629const char* MSILWriter::getLibraryName(const Function* F) {
1630 return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1631}
1632
1633
1634const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
Chris Lattnerb8158ac2009-07-14 18:17:16 +00001635 return getLibraryForSymbol(Mang->getMangledName(GV).c_str(), false, 0);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001636}
1637
1638
1639const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1640 unsigned CallingConv) {
1641 // TODO: Read *.def file with function and libraries definitions.
1642 return "MSVCRT.DLL";
1643}
1644
1645
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001646void MSILWriter::printExternals() {
1647 Module::const_iterator I,E;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001648 // Functions.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001649 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1650 // Skip intrisics
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001651 if (I->isIntrinsic()) continue;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001652 if (I->isDeclaration()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001653 const Function* F = I;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001654 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001655 std::string Sig =
1656 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1657 Out << ".method static hidebysig pinvokeimpl(\""
1658 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001659 }
1660 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001661 // External variables and static initialization.
1662 Out <<
1663 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1664 " native int LoadLibrary(string) preservesig {}\n"
1665 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1666 " native int GetProcAddress(native int, string) preservesig {}\n";
1667 Out <<
1668 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1669 " managed cil\n{\n"
1670 "\tldarg\tlib\n"
1671 "\tcall\tnative int LoadLibrary(string)\n"
1672 "\tldarg\tsym\n"
1673 "\tcall\tnative int GetProcAddress(native int,string)\n"
1674 "\tdup\n"
1675 "\tbrtrue\tL_01\n"
1676 "\tldstr\t\"Can no import variable\"\n"
1677 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1678 "\tthrow\n"
1679 "L_01:\n"
1680 "\tret\n"
1681 "}\n\n"
1682 ".method static private void $MSIL_Init() managed cil\n{\n";
1683 printStaticInitializerList();
1684 // Foreach global variable.
1685 for (Module::global_iterator I = ModulePtr->global_begin(),
1686 E = ModulePtr->global_end(); I!=E; ++I) {
1687 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1688 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1689 std::string Label = "not_null$_"+utostr(getUniqID());
1690 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1691 printSimpleInstruction("ldsflda",Tmp.c_str());
1692 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
Chris Lattnerb8158ac2009-07-14 18:17:16 +00001693 Out << "\tldstr\t\"" << Mang->getMangledName(&*I) << "\"\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001694 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1695 printIndirectSave(I->getType());
1696 }
1697 printSimpleInstruction("ret");
1698 Out << "}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001699}
1700
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001701
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001702//===----------------------------------------------------------------------===//
Bill Wendling85db3a92008-02-26 10:57:23 +00001703// External Interface declaration
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001704//===----------------------------------------------------------------------===//
1705
David Greene71847812009-07-14 20:18:05 +00001706bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1707 formatted_raw_ostream &o,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001708 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00001709 CodeGenOpt::Level OptLevel)
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001710{
1711 if (FileType != TargetMachine::AssemblyFile) return true;
1712 MSILWriter* Writer = new MSILWriter(o);
Gordon Henriksence224772008-01-07 01:30:38 +00001713 PM.add(createGCLoweringPass());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001714 PM.add(createLowerAllocationsPass(true));
1715 // FIXME: Handle switch trougth native IL instruction "switch"
1716 PM.add(createLowerSwitchPass());
1717 PM.add(createCFGSimplificationPass());
1718 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1719 PM.add(Writer);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001720 PM.add(createGCInfoDeleter());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001721 return false;
1722}