blob: b1239a2c4c121bc63eba63d04f61b2c1042e31f5 [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; }
Owen Andersoncb371882008-08-21 00:14:44 +000038 virtual bool addPassesToEmitWholeFile(PassManager &PM, raw_ostream &Out,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000039 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +000040 CodeGenOpt::Level OptLevel);
Anton Korobeynikov099883f2007-03-21 21:38:25 +000041
42 // This class always works, but shouldn't be the default in most cases.
43 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
44
45 virtual const TargetData *getTargetData() const { return &DataLayout; }
46 };
47}
48
Oscar Fuentes92adc192008-11-15 21:36:30 +000049/// MSILTargetMachineModule - Note that this is used on hosts that
50/// cannot link in a library unless there are references into the
51/// library. In particular, it seems that it is not possible to get
52/// things to work on Win32 without this. Though it is unused, do not
53/// remove it.
54extern "C" int MSILTargetMachineModule;
55int MSILTargetMachineModule = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000056
Dan Gohmanb8cab922008-10-14 20:25:08 +000057static RegisterTarget<MSILTarget> X("msil", "MSIL backend");
Anton Korobeynikov099883f2007-03-21 21:38:25 +000058
Bob Wilsona96751f2009-06-23 23:59:40 +000059// Force static initialization.
60extern "C" void LLVMInitializeMSILTarget() { }
Douglas Gregor1555a232009-06-16 20:12:29 +000061
Anton Korobeynikov099883f2007-03-21 21:38:25 +000062bool MSILModule::runOnModule(Module &M) {
63 ModulePtr = &M;
64 TD = &getAnalysis<TargetData>();
65 bool Changed = false;
66 // Find named types.
67 TypeSymbolTable& Table = M.getTypeSymbolTable();
68 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
69 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
70 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
71 Table.remove(I++);
72 else {
73 std::set<const Type *>::iterator T = Types.find(I->second);
74 if (T==Types.end())
75 Table.remove(I++);
76 else {
77 Types.erase(T);
78 ++I;
79 }
80 }
81 }
82 // Find unnamed types.
83 unsigned RenameCounter = 0;
84 for (std::set<const Type *>::const_iterator I = Types.begin(),
85 E = Types.end(); I!=E; ++I)
86 if (const StructType *STy = dyn_cast<StructType>(*I)) {
87 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
88 ++RenameCounter;
89 Changed = true;
90 }
91 // Pointer for FunctionPass.
92 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
93 return Changed;
94}
95
Devang Patel19974732007-05-03 01:11:54 +000096char MSILModule::ID = 0;
97char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000098
99bool MSILWriter::runOnFunction(Function &F) {
100 if (F.isDeclaration()) return false;
Chris Lattner9062d9a2009-04-17 00:26:12 +0000101
102 // Do not codegen any 'available_externally' functions at all, they have
103 // definitions outside the translation unit.
104 if (F.hasAvailableExternallyLinkage())
105 return false;
106
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000107 LInfo = &getAnalysis<LoopInfo>();
108 printFunction(F);
109 return false;
110}
111
112
113bool MSILWriter::doInitialization(Module &M) {
114 ModulePtr = &M;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000115 Mang = new Mangler(M);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000116 Out << ".assembly extern mscorlib {}\n";
117 Out << ".assembly MSIL {}\n\n";
118 Out << "// External\n";
119 printExternals();
120 Out << "// Declarations\n";
121 printDeclarations(M.getTypeSymbolTable());
122 Out << "// Definitions\n";
123 printGlobalVariables();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000124 Out << "// Startup code\n";
125 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000126 return false;
127}
128
129
130bool MSILWriter::doFinalization(Module &M) {
131 delete Mang;
132 return false;
133}
134
135
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000136void MSILWriter::printModuleStartup() {
137 Out <<
138 ".method static public int32 $MSIL_Startup() {\n"
139 "\t.entrypoint\n"
140 "\t.locals (native int i)\n"
141 "\t.locals (native int argc)\n"
142 "\t.locals (native int ptr)\n"
143 "\t.locals (void* argv)\n"
144 "\t.locals (string[] args)\n"
145 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
146 "\tdup\n"
147 "\tstloc\targs\n"
148 "\tldlen\n"
149 "\tconv.i4\n"
150 "\tdup\n"
151 "\tstloc\targc\n";
152 printPtrLoad(TD->getPointerSize());
153 Out <<
154 "\tmul\n"
155 "\tlocalloc\n"
156 "\tstloc\targv\n"
157 "\tldc.i4.0\n"
158 "\tstloc\ti\n"
159 "L_01:\n"
160 "\tldloc\ti\n"
161 "\tldloc\targc\n"
162 "\tceq\n"
163 "\tbrtrue\tL_02\n"
164 "\tldloc\targs\n"
165 "\tldloc\ti\n"
166 "\tldelem.ref\n"
167 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
168 "StringToHGlobalAnsi(string)\n"
169 "\tstloc\tptr\n"
170 "\tldloc\targv\n"
171 "\tldloc\ti\n";
172 printPtrLoad(TD->getPointerSize());
173 Out <<
174 "\tmul\n"
175 "\tadd\n"
176 "\tldloc\tptr\n"
177 "\tstind.i\n"
178 "\tldloc\ti\n"
179 "\tldc.i4.1\n"
180 "\tadd\n"
181 "\tstloc\ti\n"
182 "\tbr\tL_01\n"
183 "L_02:\n"
184 "\tcall void $MSIL_Init()\n";
185
186 // Call user 'main' function.
187 const Function* F = ModulePtr->getFunction("main");
188 if (!F || F->isDeclaration()) {
189 Out << "\tldc.i4.0\n\tret\n}\n";
190 return;
191 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000192 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000193 std::string Args("");
194 Function::const_arg_iterator Arg1,Arg2;
195
196 switch (F->arg_size()) {
197 case 0:
198 BadSig = false;
199 break;
200 case 1:
201 Arg1 = F->arg_begin();
202 if (Arg1->getType()->isInteger()) {
203 Out << "\tldloc\targc\n";
204 Args = getTypeName(Arg1->getType());
205 BadSig = false;
206 }
207 break;
208 case 2:
209 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
210 if (Arg1->getType()->isInteger() &&
211 Arg2->getType()->getTypeID() == Type::PointerTyID) {
212 Out << "\tldloc\targc\n\tldloc\targv\n";
213 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
214 BadSig = false;
215 }
216 break;
217 default:
218 BadSig = true;
219 }
220
221 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
Anton Korobeynikov7c1c2612008-02-20 11:22:39 +0000222 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000223 Out << "\tldc.i4.0\n";
224 } else {
225 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
226 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
227 if (RetVoid)
228 Out << "\tldc.i4.0\n";
229 else
230 Out << "\tconv.i4\n";
231 }
232 Out << "\tret\n}\n";
233}
234
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000235bool MSILWriter::isZeroValue(const Value* V) {
236 if (const Constant *C = dyn_cast<Constant>(V))
237 return C->isNullValue();
238 return false;
239}
240
241
242std::string MSILWriter::getValueName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000243 std::string Name;
244 if (const GlobalValue *GV = cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000245 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000246 else {
247 unsigned &No = AnonValueNumbers[V];
248 if (No == 0) No = ++NextAnonValueNumber;
249 Name = "tmp" + utostr(No);
250 }
251
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000252 // Name into the quotes allow control and space characters.
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000253 return "'"+Name+"'";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000254}
255
256
257std::string MSILWriter::getLabelName(const std::string& Name) {
258 if (Name.find('.')!=std::string::npos) {
259 std::string Tmp(Name);
260 // Replace unaccepable characters in the label name.
261 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
262 if (*I=='.') *I = '@';
263 return Tmp;
264 }
265 return Name;
266}
267
268
269std::string MSILWriter::getLabelName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000270 std::string Name;
271 if (const GlobalValue *GV = cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000272 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000273 else {
274 unsigned &No = AnonValueNumbers[V];
275 if (No == 0) No = ++NextAnonValueNumber;
276 Name = "tmp" + utostr(No);
277 }
278
279 return getLabelName(Name);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000280}
281
282
283std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
284 switch (CallingConvID) {
285 case CallingConv::C:
286 case CallingConv::Cold:
287 case CallingConv::Fast:
288 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
289 case CallingConv::X86_FastCall:
290 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
291 case CallingConv::X86_StdCall:
292 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
293 default:
294 cerr << "CallingConvID = " << CallingConvID << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000295 llvm_unreachable("Unsupported calling convention");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000296 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000297 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000298}
299
300
301std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
302 std::string Tmp = "";
303 const Type* ElemTy = Ty;
304 assert(Ty->getTypeID()==TyID && "Invalid type passed");
305 // Walk trought array element types.
306 for (;;) {
307 // Multidimensional array.
308 if (ElemTy->getTypeID()==TyID) {
309 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
310 Tmp += utostr(ATy->getNumElements());
311 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
312 Tmp += utostr(VTy->getNumElements());
313 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
314 }
315 // Base element type found.
316 if (ElemTy->getTypeID()!=TyID) break;
317 Tmp += ",";
318 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000319 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000320}
321
322
323std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
324 unsigned NumBits = 0;
325 switch (Ty->getTypeID()) {
326 case Type::VoidTyID:
327 return "void ";
328 case Type::IntegerTyID:
329 NumBits = getBitWidth(Ty);
330 if(NumBits==1)
331 return "bool ";
332 if (!isSigned)
333 return "unsigned int"+utostr(NumBits)+" ";
334 return "int"+utostr(NumBits)+" ";
335 case Type::FloatTyID:
336 return "float32 ";
337 case Type::DoubleTyID:
338 return "float64 ";
339 default:
340 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000341 llvm_unreachable("Invalid primitive type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000342 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000343 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000344}
345
346
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000347std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
348 bool isNested) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000349 if (Ty->isPrimitiveType() || Ty->isInteger())
350 return getPrimitiveTypeName(Ty,isSigned);
351 // FIXME: "OpaqueType" support
352 switch (Ty->getTypeID()) {
353 case Type::PointerTyID:
354 return "void* ";
355 case Type::StructTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000356 if (isNested)
357 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000358 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
359 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000360 if (isNested)
361 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000362 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
363 case Type::VectorTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000364 if (isNested)
365 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000366 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
367 default:
368 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000369 llvm_unreachable("Invalid type in getTypeName()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000370 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000371 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000372}
373
374
375MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
376 // Function argument
377 if (isa<Argument>(V))
378 return ArgumentVT;
379 // Function
380 else if (const Function* F = dyn_cast<Function>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000381 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000382 // Variable
383 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000384 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000385 // Constant
386 else if (isa<Constant>(V))
387 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
388 // Local variable
389 return LocalVT;
390}
391
392
393std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
394 bool isSigned) {
395 unsigned NumBits = 0;
396 switch (Ty->getTypeID()) {
397 // Integer constant, expanding for stack operations.
398 case Type::IntegerTyID:
399 NumBits = getBitWidth(Ty);
400 // Expand integer value to "int32" or "int64".
401 if (Expand) return (NumBits<=32 ? "i4" : "i8");
402 if (NumBits==1) return "i1";
403 return (isSigned ? "i" : "u")+utostr(NumBits/8);
404 // Float constant.
405 case Type::FloatTyID:
406 return "r4";
407 case Type::DoubleTyID:
408 return "r8";
409 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +0000410 return "i"+utostr(TD->getTypeAllocSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000411 default:
412 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000413 llvm_unreachable("Invalid type in TypeToPostfix()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000414 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000415 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000416}
417
418
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000419void MSILWriter::printConvToPtr() {
420 switch (ModulePtr->getPointerSize()) {
421 case Module::Pointer32:
422 printSimpleInstruction("conv.u4");
423 break;
424 case Module::Pointer64:
425 printSimpleInstruction("conv.u8");
426 break;
427 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000428 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000429 }
430}
431
432
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000433void MSILWriter::printPtrLoad(uint64_t N) {
434 switch (ModulePtr->getPointerSize()) {
435 case Module::Pointer32:
436 printSimpleInstruction("ldc.i4",utostr(N).c_str());
437 // FIXME: Need overflow test?
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000438 if (!isUInt32(N)) {
439 cerr << "Value = " << utostr(N) << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000440 llvm_unreachable("32-bit pointer overflowed");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000441 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000442 break;
443 case Module::Pointer64:
444 printSimpleInstruction("ldc.i8",utostr(N).c_str());
445 break;
446 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000447 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000448 }
449}
450
451
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000452void MSILWriter::printValuePtrLoad(const Value* V) {
453 printValueLoad(V);
454 printConvToPtr();
455}
456
457
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000458void MSILWriter::printConstLoad(const Constant* C) {
459 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
460 // Integer constant
461 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
462 if (CInt->isMinValue(true))
463 Out << CInt->getSExtValue();
464 else
465 Out << CInt->getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000466 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000467 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000468 uint64_t X;
469 unsigned Size;
470 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000471 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000472 Size = 4;
473 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000474 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000475 Size = 8;
476 }
477 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
478 } else if (isa<UndefValue>(C)) {
479 // Undefined constant value = NULL.
480 printPtrLoad(0);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000481 } else {
482 cerr << "Constant = " << *C << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000483 llvm_unreachable("Invalid constant value");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000484 }
485 Out << '\n';
486}
487
488
489void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000490 MSILWriter::ValueType Location = getValueLocation(V);
491 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000492 // Global variable or function address.
493 case GlobalVT:
494 case InternalVT:
495 if (const Function* F = dyn_cast<Function>(V)) {
496 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
497 printSimpleInstruction("ldftn",
498 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
499 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000500 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000501 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000502 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
503 Tmp = "void* "+getValueName(V);
504 printSimpleInstruction("ldsfld",Tmp.c_str());
505 } else {
506 Tmp = getTypeName(ElemTy)+getValueName(V);
507 printSimpleInstruction("ldsflda",Tmp.c_str());
508 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000509 }
510 break;
511 // Function argument.
512 case ArgumentVT:
513 printSimpleInstruction("ldarg",getValueName(V).c_str());
514 break;
515 // Local function variable.
516 case LocalVT:
517 printSimpleInstruction("ldloc",getValueName(V).c_str());
518 break;
519 // Constant value.
520 case ConstVT:
521 if (isa<ConstantPointerNull>(V))
522 printPtrLoad(0);
523 else
524 printConstLoad(cast<Constant>(V));
525 break;
526 // Constant expression.
527 case ConstExprVT:
528 printConstantExpr(cast<ConstantExpr>(V));
529 break;
530 default:
531 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000532 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000533 }
534}
535
536
537void MSILWriter::printValueSave(const Value* V) {
538 switch (getValueLocation(V)) {
539 case ArgumentVT:
540 printSimpleInstruction("starg",getValueName(V).c_str());
541 break;
542 case LocalVT:
543 printSimpleInstruction("stloc",getValueName(V).c_str());
544 break;
545 default:
546 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000547 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000548 }
549}
550
551
552void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
553 const Value* Right) {
554 printValueLoad(Left);
555 printValueLoad(Right);
556 Out << '\t' << Name << '\n';
557}
558
559
560void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
561 if(Operand)
562 Out << '\t' << Inst << '\t' << Operand << '\n';
563 else
564 Out << '\t' << Inst << '\n';
565}
566
567
568void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
569 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
570 isa<PHINode>(I); ++I) {
571 const PHINode* Phi = cast<PHINode>(I);
572 const Value* Val = Phi->getIncomingValueForBlock(Src);
573 if (isa<UndefValue>(Val)) continue;
574 printValueLoad(Val);
575 printValueSave(Phi);
576 }
577}
578
579
580void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
581 const BasicBlock* TrueBB,
582 const BasicBlock* FalseBB) {
583 if (TrueBB==FalseBB) {
584 // "TrueBB" and "FalseBB" destination equals
585 printPHICopy(CurrBB,TrueBB);
586 printSimpleInstruction("pop");
587 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
588 } else if (FalseBB==NULL) {
589 // If "FalseBB" not used the jump have condition
590 printPHICopy(CurrBB,TrueBB);
591 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
592 } else if (TrueBB==NULL) {
593 // If "TrueBB" not used the jump is unconditional
594 printPHICopy(CurrBB,FalseBB);
595 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
596 } else {
597 // Copy PHI instructions for each block
598 std::string TmpLabel;
599 // Print PHI instructions for "TrueBB"
600 if (isa<PHINode>(TrueBB->begin())) {
601 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
602 printSimpleInstruction("brtrue",TmpLabel.c_str());
603 } else {
604 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
605 }
606 // Print PHI instructions for "FalseBB"
607 if (isa<PHINode>(FalseBB->begin())) {
608 printPHICopy(CurrBB,FalseBB);
609 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
610 } else {
611 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
612 }
613 if (isa<PHINode>(TrueBB->begin())) {
614 // Handle "TrueBB" PHI Copy
615 Out << TmpLabel << ":\n";
616 printPHICopy(CurrBB,TrueBB);
617 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
618 }
619 }
620}
621
622
623void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
624 if (Inst->isUnconditional()) {
625 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
626 } else {
627 printValueLoad(Inst->getCondition());
628 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
629 Inst->getSuccessor(1));
630 }
631}
632
633
634void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
635 const Value* VFalse) {
636 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
637 printValueLoad(VTrue);
638 printValueLoad(Cond);
639 printSimpleInstruction("brtrue",TmpLabel.c_str());
640 printSimpleInstruction("pop");
641 printValueLoad(VFalse);
642 Out << TmpLabel << ":\n";
643}
644
645
646void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000647 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000648 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000649 if (const PointerType* P = dyn_cast<PointerType>(Ty))
650 Ty = P->getElementType();
651 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000652 printSimpleInstruction(Tmp.c_str());
653}
654
655
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000656void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000657 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000658 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000659 printIndirectSave(Val->getType());
660}
661
662
663void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000664 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000665 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000666 if (*postfix.begin()=='u') *postfix.begin() = 'i';
667 postfix = "stind."+postfix;
668 printSimpleInstruction(postfix.c_str());
669}
670
671
672void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000673 const Type* Ty, const Type* SrcTy) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000674 std::string Tmp("");
675 printValueLoad(V);
676 switch (Op) {
677 // Signed
678 case Instruction::SExt:
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000679 // If sign extending int, convert first from unsigned to signed
680 // with the same bit size - because otherwise we will loose the sign.
681 if (SrcTy) {
682 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
683 printSimpleInstruction(Tmp.c_str());
684 }
Bill Wendling5f544502009-07-14 18:30:04 +0000685 // FALLTHROUGH
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000686 case Instruction::SIToFP:
687 case Instruction::FPToSI:
688 Tmp = "conv."+getTypePostfix(Ty,false,true);
689 printSimpleInstruction(Tmp.c_str());
690 break;
691 // Unsigned
692 case Instruction::FPTrunc:
693 case Instruction::FPExt:
694 case Instruction::UIToFP:
695 case Instruction::Trunc:
696 case Instruction::ZExt:
697 case Instruction::FPToUI:
698 case Instruction::PtrToInt:
699 case Instruction::IntToPtr:
700 Tmp = "conv."+getTypePostfix(Ty,false);
701 printSimpleInstruction(Tmp.c_str());
702 break;
703 // Do nothing
704 case Instruction::BitCast:
705 // FIXME: meaning that ld*/st* instruction do not change data format.
706 break;
707 default:
708 cerr << "Opcode = " << Op << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000709 llvm_unreachable("Invalid conversion instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000710 }
711}
712
713
714void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
715 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000716 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000717 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000718 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000719 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000720 for (; I!=E; ++I){
721 Size = 0;
722 const Value* IndexValue = I.getOperand();
723 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
724 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
725 // Offset is the sum of all previous structure fields.
726 for (uint64_t F = 0; F<FieldIndex; ++F)
Duncan Sands777d2302009-05-09 07:06:46 +0000727 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000728 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000729 printSimpleInstruction("add");
730 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000731 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000732 Size = TD->getTypeAllocSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000733 } else {
Duncan Sands777d2302009-05-09 07:06:46 +0000734 Size = TD->getTypeAllocSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000735 }
736 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000737 if (!isZeroValue(IndexValue)) {
738 // Constant optimization.
739 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
740 if (C->getValue().isNegative()) {
741 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
742 printSimpleInstruction("sub");
743 continue;
744 } else
745 printPtrLoad(C->getZExtValue()*Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000746 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000747 printPtrLoad(Size);
748 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000749 printSimpleInstruction("mul");
750 }
751 printSimpleInstruction("add");
752 }
753 }
754}
755
756
757std::string MSILWriter::getCallSignature(const FunctionType* Ty,
758 const Instruction* Inst,
759 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000760 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000761 if (Ty->isVarArg()) Tmp += "vararg ";
762 // Name and return type.
763 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
764 // Function argument type list.
765 unsigned NumParams = Ty->getNumParams();
766 for (unsigned I = 0; I!=NumParams; ++I) {
767 if (I!=0) Tmp += ",";
768 Tmp += getTypeName(Ty->getParamType(I));
769 }
770 // CLR needs to know the exact amount of parameters received by vararg
771 // function, because caller cleans the stack.
772 if (Ty->isVarArg() && Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000773 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000774 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
775 // Print variable argument types.
776 unsigned NumOperands = Inst->getNumOperands()-Org;
777 if (NumParams<NumOperands) {
778 if (NumParams!=0) Tmp += ", ";
779 Tmp += "... , ";
780 for (unsigned J = NumParams; J!=NumOperands; ++J) {
781 if (J!=NumParams) Tmp += ", ";
782 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
783 }
784 }
785 }
786 return Tmp+")";
787}
788
789
790void MSILWriter::printFunctionCall(const Value* FnVal,
791 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000792 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000793 std::string Name = "";
794 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
795 Name = getConvModopt(Call->getCallingConv());
796 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
797 Name = getConvModopt(Invoke->getCallingConv());
798 else {
799 cerr << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000800 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000801 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000802 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000803 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000804 Name += getValueName(F);
805 printSimpleInstruction("call",
806 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
807 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000808 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000809 const PointerType* PTy = cast<PointerType>(FnVal->getType());
810 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000811 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000812 printValueLoad(FnVal);
813 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
814 }
815}
816
817
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000818void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
819 std::string Name;
820 switch (Inst->getIntrinsicID()) {
821 case Intrinsic::vastart:
822 Name = getValueName(Inst->getOperand(1));
823 Name.insert(Name.length()-1,"$valist");
824 // Obtain the argument handle.
825 printSimpleInstruction("ldloca",Name.c_str());
826 printSimpleInstruction("arglist");
827 printSimpleInstruction("call",
828 "instance void [mscorlib]System.ArgIterator::.ctor"
829 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
830 // Save as pointer type "void*"
831 printValueLoad(Inst->getOperand(1));
832 printSimpleInstruction("ldloca",Name.c_str());
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000833 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000834 break;
835 case Intrinsic::vaend:
836 // Close argument list handle.
837 printIndirectLoad(Inst->getOperand(1));
838 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
839 break;
840 case Intrinsic::vacopy:
841 // Copy "ArgIterator" valuetype.
842 printIndirectLoad(Inst->getOperand(1));
843 printIndirectLoad(Inst->getOperand(2));
844 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
845 break;
846 default:
847 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000848 llvm_unreachable("Invalid intrinsic function");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000849 }
850}
851
852
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000853void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000854 if (isa<IntrinsicInst>(Inst)) {
855 // Handle intrinsic function.
856 printIntrinsicCall(cast<IntrinsicInst>(Inst));
857 } else {
858 // Load arguments to stack and call function.
859 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
860 printValueLoad(Inst->getOperand(I));
861 printFunctionCall(Inst->getOperand(0),Inst);
862 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000863}
864
865
866void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
867 const Value* Right) {
868 switch (Predicate) {
869 case ICmpInst::ICMP_EQ:
870 printBinaryInstruction("ceq",Left,Right);
871 break;
872 case ICmpInst::ICMP_NE:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000873 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000874 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000875 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000876 printSimpleInstruction("not");
877 break;
878 case ICmpInst::ICMP_ULE:
879 case ICmpInst::ICMP_SLE:
880 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
881 printBinaryInstruction("ceq",Left,Right);
882 if (Predicate==ICmpInst::ICMP_ULE)
883 printBinaryInstruction("clt.un",Left,Right);
884 else
885 printBinaryInstruction("clt",Left,Right);
886 printSimpleInstruction("or");
887 break;
888 case ICmpInst::ICMP_UGE:
889 case ICmpInst::ICMP_SGE:
890 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
891 printBinaryInstruction("ceq",Left,Right);
892 if (Predicate==ICmpInst::ICMP_UGE)
893 printBinaryInstruction("cgt.un",Left,Right);
894 else
895 printBinaryInstruction("cgt",Left,Right);
896 printSimpleInstruction("or");
897 break;
898 case ICmpInst::ICMP_ULT:
899 printBinaryInstruction("clt.un",Left,Right);
900 break;
901 case ICmpInst::ICMP_SLT:
902 printBinaryInstruction("clt",Left,Right);
903 break;
904 case ICmpInst::ICMP_UGT:
905 printBinaryInstruction("cgt.un",Left,Right);
Anton Korobeynikove9fd67e2009-07-14 09:52:47 +0000906 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000907 case ICmpInst::ICMP_SGT:
908 printBinaryInstruction("cgt",Left,Right);
909 break;
910 default:
911 cerr << "Predicate = " << Predicate << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000912 llvm_unreachable("Invalid icmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000913 }
914}
915
916
917void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
918 const Value* Right) {
919 // FIXME: Correct comparison
920 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
921 switch (Predicate) {
922 case FCmpInst::FCMP_UGT:
923 // X > Y || llvm_fcmp_uno(X, Y)
924 printBinaryInstruction("cgt",Left,Right);
925 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
926 printSimpleInstruction("or");
927 break;
928 case FCmpInst::FCMP_OGT:
929 // X > Y
930 printBinaryInstruction("cgt",Left,Right);
931 break;
932 case FCmpInst::FCMP_UGE:
933 // X >= Y || llvm_fcmp_uno(X, Y)
934 printBinaryInstruction("ceq",Left,Right);
935 printBinaryInstruction("cgt",Left,Right);
936 printSimpleInstruction("or");
937 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
938 printSimpleInstruction("or");
939 break;
940 case FCmpInst::FCMP_OGE:
941 // X >= Y
942 printBinaryInstruction("ceq",Left,Right);
943 printBinaryInstruction("cgt",Left,Right);
944 printSimpleInstruction("or");
945 break;
946 case FCmpInst::FCMP_ULT:
947 // X < Y || llvm_fcmp_uno(X, Y)
948 printBinaryInstruction("clt",Left,Right);
949 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
950 printSimpleInstruction("or");
951 break;
952 case FCmpInst::FCMP_OLT:
953 // X < Y
954 printBinaryInstruction("clt",Left,Right);
955 break;
956 case FCmpInst::FCMP_ULE:
957 // X <= Y || llvm_fcmp_uno(X, Y)
958 printBinaryInstruction("ceq",Left,Right);
959 printBinaryInstruction("clt",Left,Right);
960 printSimpleInstruction("or");
961 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
962 printSimpleInstruction("or");
963 break;
964 case FCmpInst::FCMP_OLE:
965 // X <= Y
966 printBinaryInstruction("ceq",Left,Right);
967 printBinaryInstruction("clt",Left,Right);
968 printSimpleInstruction("or");
969 break;
970 case FCmpInst::FCMP_UEQ:
971 // X == Y || llvm_fcmp_uno(X, Y)
972 printBinaryInstruction("ceq",Left,Right);
973 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
974 printSimpleInstruction("or");
975 break;
976 case FCmpInst::FCMP_OEQ:
977 // X == Y
978 printBinaryInstruction("ceq",Left,Right);
979 break;
980 case FCmpInst::FCMP_UNE:
981 // X != Y
982 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000983 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000984 printSimpleInstruction("not");
985 break;
986 case FCmpInst::FCMP_ONE:
987 // X != Y && llvm_fcmp_ord(X, Y)
988 printBinaryInstruction("ceq",Left,Right);
989 printSimpleInstruction("not");
990 break;
991 case FCmpInst::FCMP_ORD:
992 // return X == X && Y == Y
993 printBinaryInstruction("ceq",Left,Left);
994 printBinaryInstruction("ceq",Right,Right);
995 printSimpleInstruction("or");
996 break;
997 case FCmpInst::FCMP_UNO:
998 // X != X || Y != Y
999 printBinaryInstruction("ceq",Left,Left);
1000 printSimpleInstruction("not");
1001 printBinaryInstruction("ceq",Right,Right);
1002 printSimpleInstruction("not");
1003 printSimpleInstruction("or");
1004 break;
1005 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001006 llvm_unreachable("Illegal FCmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001007 }
1008}
1009
1010
1011void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1012 std::string Label = "leave$normal_"+utostr(getUniqID());
1013 Out << ".try {\n";
1014 // Load arguments
1015 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1016 printValueLoad(Inst->getOperand(I));
1017 // Print call instruction
1018 printFunctionCall(Inst->getOperand(0),Inst);
1019 // Save function result and leave "try" block
1020 printValueSave(Inst);
1021 printSimpleInstruction("leave",Label.c_str());
1022 Out << "}\n";
1023 Out << "catch [mscorlib]System.Exception {\n";
1024 // Redirect to unwind block
1025 printSimpleInstruction("pop");
1026 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1027 Out << "}\n" << Label << ":\n";
1028 // Redirect to continue block
1029 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1030}
1031
1032
1033void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1034 // FIXME: Emulate with IL "switch" instruction
1035 // Emulate = if () else if () else if () else ...
1036 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1037 printValueLoad(Inst->getCondition());
1038 printValueLoad(Inst->getCaseValue(I));
1039 printSimpleInstruction("ceq");
1040 // Condition jump to successor block
1041 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1042 }
1043 // Jump to default block
1044 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1045}
1046
1047
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001048void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1049 printIndirectLoad(Inst->getOperand(0));
1050 printSimpleInstruction("call",
1051 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1052 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001053 std::string Name =
1054 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001055 printSimpleInstruction(Name.c_str());
1056}
1057
1058
1059void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
Duncan Sands777d2302009-05-09 07:06:46 +00001060 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001061 // Constant optimization.
1062 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1063 printPtrLoad(CInt->getZExtValue()*Size);
1064 } else {
1065 printPtrLoad(Size);
1066 printValueLoad(Inst->getOperand(0));
1067 printSimpleInstruction("mul");
1068 }
1069 printSimpleInstruction("localloc");
1070}
1071
1072
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001073void MSILWriter::printInstruction(const Instruction* Inst) {
1074 const Value *Left = 0, *Right = 0;
1075 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1076 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1077 // Print instruction
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001078 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001079 switch (Inst->getOpcode()) {
1080 // Terminator
1081 case Instruction::Ret:
1082 if (Inst->getNumOperands()) {
1083 printValueLoad(Left);
1084 printSimpleInstruction("ret");
1085 } else
1086 printSimpleInstruction("ret");
1087 break;
1088 case Instruction::Br:
1089 printBranchInstruction(cast<BranchInst>(Inst));
1090 break;
1091 // Binary
1092 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001093 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001094 printBinaryInstruction("add",Left,Right);
1095 break;
1096 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001097 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001098 printBinaryInstruction("sub",Left,Right);
1099 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001100 case Instruction::Mul:
1101 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001102 printBinaryInstruction("mul",Left,Right);
1103 break;
1104 case Instruction::UDiv:
1105 printBinaryInstruction("div.un",Left,Right);
1106 break;
1107 case Instruction::SDiv:
1108 case Instruction::FDiv:
1109 printBinaryInstruction("div",Left,Right);
1110 break;
1111 case Instruction::URem:
1112 printBinaryInstruction("rem.un",Left,Right);
1113 break;
1114 case Instruction::SRem:
1115 case Instruction::FRem:
1116 printBinaryInstruction("rem",Left,Right);
1117 break;
1118 // Binary Condition
1119 case Instruction::ICmp:
1120 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1121 break;
1122 case Instruction::FCmp:
1123 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1124 break;
1125 // Bitwise Binary
1126 case Instruction::And:
1127 printBinaryInstruction("and",Left,Right);
1128 break;
1129 case Instruction::Or:
1130 printBinaryInstruction("or",Left,Right);
1131 break;
1132 case Instruction::Xor:
1133 printBinaryInstruction("xor",Left,Right);
1134 break;
1135 case Instruction::Shl:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001136 printValueLoad(Left);
1137 printValueLoad(Right);
1138 printSimpleInstruction("conv.i4");
1139 printSimpleInstruction("shl");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001140 break;
1141 case Instruction::LShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001142 printValueLoad(Left);
1143 printValueLoad(Right);
1144 printSimpleInstruction("conv.i4");
1145 printSimpleInstruction("shr.un");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001146 break;
1147 case Instruction::AShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001148 printValueLoad(Left);
1149 printValueLoad(Right);
1150 printSimpleInstruction("conv.i4");
1151 printSimpleInstruction("shr");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001152 break;
1153 case Instruction::Select:
1154 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1155 break;
1156 case Instruction::Load:
1157 printIndirectLoad(Inst->getOperand(0));
1158 break;
1159 case Instruction::Store:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001160 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001161 break;
Anton Korobeynikov94ac0342009-07-14 09:53:14 +00001162 case Instruction::SExt:
1163 printCastInstruction(Inst->getOpcode(),Left,
1164 cast<CastInst>(Inst)->getDestTy(),
1165 cast<CastInst>(Inst)->getSrcTy());
1166 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001167 case Instruction::Trunc:
1168 case Instruction::ZExt:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001169 case Instruction::FPTrunc:
1170 case Instruction::FPExt:
1171 case Instruction::UIToFP:
1172 case Instruction::SIToFP:
1173 case Instruction::FPToUI:
1174 case Instruction::FPToSI:
1175 case Instruction::PtrToInt:
1176 case Instruction::IntToPtr:
1177 case Instruction::BitCast:
1178 printCastInstruction(Inst->getOpcode(),Left,
1179 cast<CastInst>(Inst)->getDestTy());
1180 break;
1181 case Instruction::GetElementPtr:
1182 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1183 gep_type_end(Inst));
1184 break;
1185 case Instruction::Call:
1186 printCallInstruction(cast<CallInst>(Inst));
1187 break;
1188 case Instruction::Invoke:
1189 printInvokeInstruction(cast<InvokeInst>(Inst));
1190 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001191 case Instruction::Unwind:
1192 printSimpleInstruction("newobj",
1193 "instance void [mscorlib]System.Exception::.ctor()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001194 printSimpleInstruction("throw");
1195 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001196 case Instruction::Switch:
1197 printSwitchInstruction(cast<SwitchInst>(Inst));
1198 break;
1199 case Instruction::Alloca:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001200 printAllocaInstruction(cast<AllocaInst>(Inst));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001201 break;
1202 case Instruction::Malloc:
Torok Edwinc23197a2009-07-14 16:55:14 +00001203 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001204 break;
1205 case Instruction::Free:
Torok Edwinc23197a2009-07-14 16:55:14 +00001206 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001207 break;
1208 case Instruction::Unreachable:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001209 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1210 printSimpleInstruction("newobj",
1211 "instance void [mscorlib]System.Exception::.ctor(string)");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001212 printSimpleInstruction("throw");
1213 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001214 case Instruction::VAArg:
1215 printVAArgInstruction(cast<VAArgInst>(Inst));
1216 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001217 default:
1218 cerr << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001219 llvm_unreachable("Unsupported instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001220 }
1221}
1222
1223
1224void MSILWriter::printLoop(const Loop* L) {
1225 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1226 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1227 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1228 BasicBlock* BB = blocks[I];
1229 Loop* BBLoop = LInfo->getLoopFor(BB);
1230 if (BBLoop == L)
1231 printBasicBlock(BB);
1232 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1233 printLoop(BBLoop);
1234 }
1235 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1236}
1237
1238
1239void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1240 Out << getLabelName(BB) << ":\n";
1241 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1242 const Instruction* Inst = I;
1243 // Comment llvm original instruction
Owen Andersoncb371882008-08-21 00:14:44 +00001244 // Out << "\n//" << *Inst << "\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001245 // Do not handle PHI instruction in current block
1246 if (Inst->getOpcode()==Instruction::PHI) continue;
1247 // Print instruction
1248 printInstruction(Inst);
1249 // Save result
1250 if (Inst->getType()!=Type::VoidTy) {
1251 // Do not save value after invoke, it done in "try" block
1252 if (Inst->getOpcode()==Instruction::Invoke) continue;
1253 printValueSave(Inst);
1254 }
1255 }
1256}
1257
1258
1259void MSILWriter::printLocalVariables(const Function& F) {
1260 std::string Name;
1261 const Type* Ty = NULL;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001262 std::set<const Value*> Printed;
1263 const Value* VaList = NULL;
1264 unsigned StackDepth = 8;
1265 // Find local variables
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001266 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001267 if (I->getOpcode()==Instruction::Call ||
1268 I->getOpcode()==Instruction::Invoke) {
1269 // Test stack depth.
1270 if (StackDepth<I->getNumOperands())
1271 StackDepth = I->getNumOperands();
1272 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001273 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1274 if (AI && !isa<GlobalVariable>(AI)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001275 // Local variable allocation.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001276 Ty = PointerType::getUnqual(AI->getAllocatedType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001277 Name = getValueName(AI);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001278 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001279 } else if (I->getType()!=Type::VoidTy) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001280 // Operation result.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001281 Ty = I->getType();
1282 Name = getValueName(&*I);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001283 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1284 }
1285 // Test on 'va_list' variable
1286 bool isVaList = false;
1287 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1288 // "va_list" as "va_arg" instruction operand.
1289 isVaList = true;
1290 VaList = VaInst->getOperand(0);
1291 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1292 // "va_list" as intrinsic function operand.
1293 switch (Inst->getIntrinsicID()) {
1294 case Intrinsic::vastart:
1295 case Intrinsic::vaend:
1296 case Intrinsic::vacopy:
1297 isVaList = true;
1298 VaList = Inst->getOperand(1);
1299 break;
1300 default:
1301 isVaList = false;
1302 }
1303 }
1304 // Print "va_list" variable.
1305 if (isVaList && Printed.insert(VaList).second) {
1306 Name = getValueName(VaList);
1307 Name.insert(Name.length()-1,"$valist");
1308 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1309 << Name << ")\n";
1310 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001311 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001312 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001313}
1314
1315
1316void MSILWriter::printFunctionBody(const Function& F) {
1317 // Print body
1318 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1319 if (Loop *L = LInfo->getLoopFor(I)) {
1320 if (L->getHeader()==I && L->getParentLoop()==0)
1321 printLoop(L);
1322 } else {
1323 printBasicBlock(I);
1324 }
1325 }
1326}
1327
1328
1329void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1330 const Value *left = 0, *right = 0;
1331 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1332 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1333 // Print instruction
1334 switch (CE->getOpcode()) {
1335 case Instruction::Trunc:
1336 case Instruction::ZExt:
1337 case Instruction::SExt:
1338 case Instruction::FPTrunc:
1339 case Instruction::FPExt:
1340 case Instruction::UIToFP:
1341 case Instruction::SIToFP:
1342 case Instruction::FPToUI:
1343 case Instruction::FPToSI:
1344 case Instruction::PtrToInt:
1345 case Instruction::IntToPtr:
1346 case Instruction::BitCast:
1347 printCastInstruction(CE->getOpcode(),left,CE->getType());
1348 break;
1349 case Instruction::GetElementPtr:
1350 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1351 break;
1352 case Instruction::ICmp:
1353 printICmpInstruction(CE->getPredicate(),left,right);
1354 break;
1355 case Instruction::FCmp:
1356 printFCmpInstruction(CE->getPredicate(),left,right);
1357 break;
1358 case Instruction::Select:
1359 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1360 break;
1361 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001362 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001363 printBinaryInstruction("add",left,right);
1364 break;
1365 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001366 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001367 printBinaryInstruction("sub",left,right);
1368 break;
1369 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001370 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001371 printBinaryInstruction("mul",left,right);
1372 break;
1373 case Instruction::UDiv:
1374 printBinaryInstruction("div.un",left,right);
1375 break;
1376 case Instruction::SDiv:
1377 case Instruction::FDiv:
1378 printBinaryInstruction("div",left,right);
1379 break;
1380 case Instruction::URem:
1381 printBinaryInstruction("rem.un",left,right);
1382 break;
1383 case Instruction::SRem:
1384 case Instruction::FRem:
1385 printBinaryInstruction("rem",left,right);
1386 break;
1387 case Instruction::And:
1388 printBinaryInstruction("and",left,right);
1389 break;
1390 case Instruction::Or:
1391 printBinaryInstruction("or",left,right);
1392 break;
1393 case Instruction::Xor:
1394 printBinaryInstruction("xor",left,right);
1395 break;
1396 case Instruction::Shl:
1397 printBinaryInstruction("shl",left,right);
1398 break;
1399 case Instruction::LShr:
1400 printBinaryInstruction("shr.un",left,right);
1401 break;
1402 case Instruction::AShr:
1403 printBinaryInstruction("shr",left,right);
1404 break;
1405 default:
1406 cerr << "Expression = " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001407 llvm_unreachable("Invalid constant expression");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001408 }
1409}
1410
1411
1412void MSILWriter::printStaticInitializerList() {
1413 // List of global variables with uninitialized fields.
1414 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1415 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1416 ++VarI) {
1417 const std::vector<StaticInitializer>& InitList = VarI->second;
1418 if (InitList.empty()) continue;
1419 // For each uninitialized field.
1420 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1421 E = InitList.end(); I!=E; ++I) {
1422 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
Owen Andersoncb371882008-08-21 00:14:44 +00001423 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1424 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001425 // Load variable address
1426 printValueLoad(VarI->first);
1427 // Add offset
1428 if (I->offset!=0) {
1429 printPtrLoad(I->offset);
1430 printSimpleInstruction("add");
1431 }
1432 // Load value
1433 printConstantExpr(CE);
1434 // Save result at offset
1435 std::string postfix = getTypePostfix(CE->getType(),true);
1436 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1437 postfix = "stind."+postfix;
1438 printSimpleInstruction(postfix.c_str());
1439 } else {
1440 cerr << "Constant = " << *I->constant << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001441 llvm_unreachable("Invalid static initializer");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001442 }
1443 }
1444 }
1445}
1446
1447
1448void MSILWriter::printFunction(const Function& F) {
Devang Patel05988662008-09-25 21:00:45 +00001449 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001450 Out << "\n.method static ";
Rafael Espindolabb46f522009-01-15 20:18:42 +00001451 Out << (F.hasLocalLinkage() ? "private " : "public ");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001452 if (F.isVarArg()) Out << "vararg ";
1453 Out << getTypeName(F.getReturnType(),isSigned) <<
1454 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1455 // Arguments
1456 Out << "\t(";
1457 unsigned ArgIdx = 1;
1458 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1459 ++I, ++ArgIdx) {
Devang Patel05988662008-09-25 21:00:45 +00001460 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001461 if (I!=F.arg_begin()) Out << ", ";
1462 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1463 }
1464 Out << ") cil managed\n";
1465 // Body
1466 Out << "{\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001467 printLocalVariables(F);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001468 printFunctionBody(F);
1469 Out << "}\n";
1470}
1471
1472
1473void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1474 std::string Name;
1475 std::set<const Type*> Printed;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001476 for (std::set<const Type*>::const_iterator
1477 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1478 const Type* Ty = *UI;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001479 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1480 Name = getTypeName(Ty, false, true);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001481 // Type with no need to declare.
1482 else continue;
1483 // Print not duplicated type
1484 if (Printed.insert(Ty).second) {
1485 Out << ".class value explicit ansi sealed '" << Name << "'";
Duncan Sands777d2302009-05-09 07:06:46 +00001486 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001487 Out << " }\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001488 }
1489 }
1490}
1491
1492
1493unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1494 unsigned int N = Ty->getPrimitiveSizeInBits();
1495 assert(N!=0 && "Invalid type in getBitWidth()");
1496 switch (N) {
1497 case 1:
1498 case 8:
1499 case 16:
1500 case 32:
1501 case 64:
1502 return N;
1503 default:
1504 cerr << "Bits = " << N << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001505 llvm_unreachable("Unsupported integer width");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001506 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001507 return 0; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001508}
1509
1510
1511void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1512 uint64_t TySize = 0;
1513 const Type* Ty = C->getType();
1514 // Print zero initialized constant.
1515 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
Duncan Sands777d2302009-05-09 07:06:46 +00001516 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001517 Offset += TySize;
1518 Out << "int8 (0) [" << TySize << "]";
1519 return;
1520 }
1521 // Print constant initializer
1522 switch (Ty->getTypeID()) {
1523 case Type::IntegerTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001524 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001525 const ConstantInt* Int = cast<ConstantInt>(C);
1526 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1527 break;
1528 }
1529 case Type::FloatTyID:
1530 case Type::DoubleTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001531 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001532 const ConstantFP* FP = cast<ConstantFP>(C);
1533 if (Ty->getTypeID() == Type::FloatTyID)
Dale Johannesen43421b32007-09-06 18:13:44 +00001534 Out << "int32 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001535 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001536 else
Dale Johannesen43421b32007-09-06 18:13:44 +00001537 Out << "int64 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001538 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001539 break;
1540 }
1541 case Type::ArrayTyID:
1542 case Type::VectorTyID:
1543 case Type::StructTyID:
1544 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1545 if (I!=0) Out << ",\n";
1546 printStaticConstant(C->getOperand(I),Offset);
1547 }
1548 break;
1549 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +00001550 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001551 // Initialize with global variable address
1552 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1553 std::string name = getValueName(G);
1554 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1555 } else {
1556 // Dynamic initialization
1557 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1558 InitListPtr->push_back(StaticInitializer(C,Offset));
1559 // Null pointer initialization
1560 if (TySize==4) Out << "int32 (0)";
1561 else if (TySize==8) Out << "int64 (0)";
Torok Edwinc23197a2009-07-14 16:55:14 +00001562 else llvm_unreachable("Invalid pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001563 }
1564 break;
1565 default:
1566 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001567 llvm_unreachable("Invalid type in printStaticConstant()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001568 }
1569 // Increase offset.
1570 Offset += TySize;
1571}
1572
1573
1574void MSILWriter::printStaticInitializer(const Constant* C,
1575 const std::string& Name) {
1576 switch (C->getType()->getTypeID()) {
1577 case Type::IntegerTyID:
1578 case Type::FloatTyID:
1579 case Type::DoubleTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001580 Out << getPrimitiveTypeName(C->getType(), false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001581 break;
1582 case Type::ArrayTyID:
1583 case Type::VectorTyID:
1584 case Type::StructTyID:
1585 case Type::PointerTyID:
1586 Out << getTypeName(C->getType());
1587 break;
1588 default:
1589 cerr << "Type = " << *C << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001590 llvm_unreachable("Invalid constant type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001591 }
1592 // Print initializer
1593 std::string label = Name;
1594 label.insert(label.length()-1,"$data");
1595 Out << Name << " at " << label << '\n';
1596 Out << ".data " << label << " = {\n";
1597 uint64_t offset = 0;
1598 printStaticConstant(C,offset);
1599 Out << "\n}\n\n";
1600}
1601
1602
1603void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1604 const Constant* C = G->getInitializer();
1605 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1606 InitListPtr = 0;
1607 else
1608 InitListPtr = &StaticInitList[G];
1609 printStaticInitializer(C,getValueName(G));
1610}
1611
1612
1613void MSILWriter::printGlobalVariables() {
1614 if (ModulePtr->global_empty()) return;
1615 Module::global_iterator I,E;
1616 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1617 // Variable definition
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001618 Out << ".field static " << (I->isDeclaration() ? "public " :
1619 "private ");
1620 if (I->isDeclaration()) {
1621 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1622 } else
1623 printVariableDefinition(&*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001624 }
1625}
1626
1627
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001628const char* MSILWriter::getLibraryName(const Function* F) {
1629 return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1630}
1631
1632
1633const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
Chris Lattnerb8158ac2009-07-14 18:17:16 +00001634 return getLibraryForSymbol(Mang->getMangledName(GV).c_str(), false, 0);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001635}
1636
1637
1638const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1639 unsigned CallingConv) {
1640 // TODO: Read *.def file with function and libraries definitions.
1641 return "MSVCRT.DLL";
1642}
1643
1644
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001645void MSILWriter::printExternals() {
1646 Module::const_iterator I,E;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001647 // Functions.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001648 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1649 // Skip intrisics
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001650 if (I->isIntrinsic()) continue;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001651 if (I->isDeclaration()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001652 const Function* F = I;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001653 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001654 std::string Sig =
1655 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1656 Out << ".method static hidebysig pinvokeimpl(\""
1657 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001658 }
1659 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001660 // External variables and static initialization.
1661 Out <<
1662 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1663 " native int LoadLibrary(string) preservesig {}\n"
1664 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1665 " native int GetProcAddress(native int, string) preservesig {}\n";
1666 Out <<
1667 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1668 " managed cil\n{\n"
1669 "\tldarg\tlib\n"
1670 "\tcall\tnative int LoadLibrary(string)\n"
1671 "\tldarg\tsym\n"
1672 "\tcall\tnative int GetProcAddress(native int,string)\n"
1673 "\tdup\n"
1674 "\tbrtrue\tL_01\n"
1675 "\tldstr\t\"Can no import variable\"\n"
1676 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1677 "\tthrow\n"
1678 "L_01:\n"
1679 "\tret\n"
1680 "}\n\n"
1681 ".method static private void $MSIL_Init() managed cil\n{\n";
1682 printStaticInitializerList();
1683 // Foreach global variable.
1684 for (Module::global_iterator I = ModulePtr->global_begin(),
1685 E = ModulePtr->global_end(); I!=E; ++I) {
1686 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1687 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1688 std::string Label = "not_null$_"+utostr(getUniqID());
1689 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1690 printSimpleInstruction("ldsflda",Tmp.c_str());
1691 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
Chris Lattnerb8158ac2009-07-14 18:17:16 +00001692 Out << "\tldstr\t\"" << Mang->getMangledName(&*I) << "\"\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001693 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1694 printIndirectSave(I->getType());
1695 }
1696 printSimpleInstruction("ret");
1697 Out << "}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001698}
1699
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001700
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001701//===----------------------------------------------------------------------===//
Bill Wendling85db3a92008-02-26 10:57:23 +00001702// External Interface declaration
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001703//===----------------------------------------------------------------------===//
1704
Owen Andersoncb371882008-08-21 00:14:44 +00001705bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM, raw_ostream &o,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001706 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00001707 CodeGenOpt::Level OptLevel)
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001708{
1709 if (FileType != TargetMachine::AssemblyFile) return true;
1710 MSILWriter* Writer = new MSILWriter(o);
Gordon Henriksence224772008-01-07 01:30:38 +00001711 PM.add(createGCLoweringPass());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001712 PM.add(createLowerAllocationsPass(true));
1713 // FIXME: Handle switch trougth native IL instruction "switch"
1714 PM.add(createLowerSwitchPass());
1715 PM.add(createCFGSimplificationPass());
1716 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1717 PM.add(Writer);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001718 PM.add(createGCInfoDeleter());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001719 return false;
1720}