blob: 1bc708eb79aa5eb669e39321bfbad09ff9caf8b7 [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"
Daniel Dunbar0c795d62009-07-25 06:49:55 +000025#include "llvm/Target/TargetRegistry.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000026#include "llvm/Transforms/Scalar.h"
27#include "llvm/ADT/StringExtras.h"
Gordon Henriksence224772008-01-07 01:30:38 +000028#include "llvm/CodeGen/Passes.h"
Nick Lewycky92fbbc72009-07-26 08:16:51 +000029using namespace llvm;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000030
Nick Lewycky92fbbc72009-07-26 08:16:51 +000031namespace llvm {
Anton Korobeynikov099883f2007-03-21 21:38:25 +000032 // TargetMachine for the MSIL
Nick Lewycky6726b6d2009-10-25 06:33:48 +000033 struct MSILTarget : public TargetMachine {
Daniel Dunbar214e2232009-08-04 04:02:45 +000034 MSILTarget(const Target &T, const std::string &TT, const std::string &FS)
35 : TargetMachine(T) {}
Anton Korobeynikov099883f2007-03-21 21:38:25 +000036
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
Daniel Dunbard1a919e2009-08-03 17:40:25 +000043 virtual const TargetData *getTargetData() const { return 0; }
Anton Korobeynikov099883f2007-03-21 21:38:25 +000044 };
45}
46
Daniel Dunbar0c795d62009-07-25 06:49:55 +000047extern "C" void LLVMInitializeMSILTarget() {
48 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000049 RegisterTargetMachine<MSILTarget> X(TheMSILTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000050}
Douglas Gregor1555a232009-06-16 20:12:29 +000051
Anton Korobeynikov099883f2007-03-21 21:38:25 +000052bool MSILModule::runOnModule(Module &M) {
53 ModulePtr = &M;
54 TD = &getAnalysis<TargetData>();
55 bool Changed = false;
56 // Find named types.
57 TypeSymbolTable& Table = M.getTypeSymbolTable();
58 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
59 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
60 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
61 Table.remove(I++);
62 else {
63 std::set<const Type *>::iterator T = Types.find(I->second);
64 if (T==Types.end())
65 Table.remove(I++);
66 else {
67 Types.erase(T);
68 ++I;
69 }
70 }
71 }
72 // Find unnamed types.
73 unsigned RenameCounter = 0;
74 for (std::set<const Type *>::const_iterator I = Types.begin(),
75 E = Types.end(); I!=E; ++I)
76 if (const StructType *STy = dyn_cast<StructType>(*I)) {
77 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
78 ++RenameCounter;
79 Changed = true;
80 }
81 // Pointer for FunctionPass.
82 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
83 return Changed;
84}
85
Devang Patel19974732007-05-03 01:11:54 +000086char MSILModule::ID = 0;
87char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000088
89bool MSILWriter::runOnFunction(Function &F) {
90 if (F.isDeclaration()) return false;
Chris Lattner9062d9a2009-04-17 00:26:12 +000091
92 // Do not codegen any 'available_externally' functions at all, they have
93 // definitions outside the translation unit.
94 if (F.hasAvailableExternallyLinkage())
95 return false;
96
Anton Korobeynikov099883f2007-03-21 21:38:25 +000097 LInfo = &getAnalysis<LoopInfo>();
98 printFunction(F);
99 return false;
100}
101
102
103bool MSILWriter::doInitialization(Module &M) {
104 ModulePtr = &M;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000105 Out << ".assembly extern mscorlib {}\n";
106 Out << ".assembly MSIL {}\n\n";
107 Out << "// External\n";
108 printExternals();
109 Out << "// Declarations\n";
110 printDeclarations(M.getTypeSymbolTable());
111 Out << "// Definitions\n";
112 printGlobalVariables();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000113 Out << "// Startup code\n";
114 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000115 return false;
116}
117
118
119bool MSILWriter::doFinalization(Module &M) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000120 return false;
121}
122
123
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000124void MSILWriter::printModuleStartup() {
125 Out <<
126 ".method static public int32 $MSIL_Startup() {\n"
127 "\t.entrypoint\n"
128 "\t.locals (native int i)\n"
129 "\t.locals (native int argc)\n"
130 "\t.locals (native int ptr)\n"
131 "\t.locals (void* argv)\n"
132 "\t.locals (string[] args)\n"
133 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
134 "\tdup\n"
135 "\tstloc\targs\n"
136 "\tldlen\n"
137 "\tconv.i4\n"
138 "\tdup\n"
139 "\tstloc\targc\n";
140 printPtrLoad(TD->getPointerSize());
141 Out <<
142 "\tmul\n"
143 "\tlocalloc\n"
144 "\tstloc\targv\n"
145 "\tldc.i4.0\n"
146 "\tstloc\ti\n"
147 "L_01:\n"
148 "\tldloc\ti\n"
149 "\tldloc\targc\n"
150 "\tceq\n"
151 "\tbrtrue\tL_02\n"
152 "\tldloc\targs\n"
153 "\tldloc\ti\n"
154 "\tldelem.ref\n"
155 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
156 "StringToHGlobalAnsi(string)\n"
157 "\tstloc\tptr\n"
158 "\tldloc\targv\n"
159 "\tldloc\ti\n";
160 printPtrLoad(TD->getPointerSize());
161 Out <<
162 "\tmul\n"
163 "\tadd\n"
164 "\tldloc\tptr\n"
165 "\tstind.i\n"
166 "\tldloc\ti\n"
167 "\tldc.i4.1\n"
168 "\tadd\n"
169 "\tstloc\ti\n"
170 "\tbr\tL_01\n"
171 "L_02:\n"
172 "\tcall void $MSIL_Init()\n";
173
174 // Call user 'main' function.
175 const Function* F = ModulePtr->getFunction("main");
176 if (!F || F->isDeclaration()) {
177 Out << "\tldc.i4.0\n\tret\n}\n";
178 return;
179 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000180 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000181 std::string Args("");
182 Function::const_arg_iterator Arg1,Arg2;
183
184 switch (F->arg_size()) {
185 case 0:
186 BadSig = false;
187 break;
188 case 1:
189 Arg1 = F->arg_begin();
190 if (Arg1->getType()->isInteger()) {
191 Out << "\tldloc\targc\n";
192 Args = getTypeName(Arg1->getType());
193 BadSig = false;
194 }
195 break;
196 case 2:
197 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
198 if (Arg1->getType()->isInteger() &&
199 Arg2->getType()->getTypeID() == Type::PointerTyID) {
200 Out << "\tldloc\targc\n\tldloc\targv\n";
201 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
202 BadSig = false;
203 }
204 break;
205 default:
206 BadSig = true;
207 }
208
209 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
Anton Korobeynikov7c1c2612008-02-20 11:22:39 +0000210 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000211 Out << "\tldc.i4.0\n";
212 } else {
213 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
214 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
215 if (RetVoid)
216 Out << "\tldc.i4.0\n";
217 else
218 Out << "\tconv.i4\n";
219 }
220 Out << "\tret\n}\n";
221}
222
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000223bool MSILWriter::isZeroValue(const Value* V) {
224 if (const Constant *C = dyn_cast<Constant>(V))
225 return C->isNullValue();
226 return false;
227}
228
229
230std::string MSILWriter::getValueName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000231 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000232 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattner27891032010-01-16 02:15:38 +0000233 Name = GV->getName();
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000234 else {
235 unsigned &No = AnonValueNumbers[V];
236 if (No == 0) No = ++NextAnonValueNumber;
237 Name = "tmp" + utostr(No);
238 }
239
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000240 // Name into the quotes allow control and space characters.
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000241 return "'"+Name+"'";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000242}
243
244
245std::string MSILWriter::getLabelName(const std::string& Name) {
246 if (Name.find('.')!=std::string::npos) {
247 std::string Tmp(Name);
248 // Replace unaccepable characters in the label name.
249 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
250 if (*I=='.') *I = '@';
251 return Tmp;
252 }
253 return Name;
254}
255
256
257std::string MSILWriter::getLabelName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000258 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000259 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattner27891032010-01-16 02:15:38 +0000260 Name = GV->getName();
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000261 else {
262 unsigned &No = AnonValueNumbers[V];
263 if (No == 0) No = ++NextAnonValueNumber;
264 Name = "tmp" + utostr(No);
265 }
266
267 return getLabelName(Name);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000268}
269
270
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000271std::string MSILWriter::getConvModopt(CallingConv::ID CallingConvID) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000272 switch (CallingConvID) {
273 case CallingConv::C:
274 case CallingConv::Cold:
275 case CallingConv::Fast:
276 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
277 case CallingConv::X86_FastCall:
278 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
279 case CallingConv::X86_StdCall:
280 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
281 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000282 errs() << "CallingConvID = " << CallingConvID << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000283 llvm_unreachable("Unsupported calling convention");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000284 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000285 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000286}
287
288
289std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
290 std::string Tmp = "";
291 const Type* ElemTy = Ty;
292 assert(Ty->getTypeID()==TyID && "Invalid type passed");
293 // Walk trought array element types.
294 for (;;) {
295 // Multidimensional array.
296 if (ElemTy->getTypeID()==TyID) {
297 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
298 Tmp += utostr(ATy->getNumElements());
299 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
300 Tmp += utostr(VTy->getNumElements());
301 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
302 }
303 // Base element type found.
304 if (ElemTy->getTypeID()!=TyID) break;
305 Tmp += ",";
306 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000307 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000308}
309
310
311std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
312 unsigned NumBits = 0;
313 switch (Ty->getTypeID()) {
314 case Type::VoidTyID:
315 return "void ";
316 case Type::IntegerTyID:
317 NumBits = getBitWidth(Ty);
318 if(NumBits==1)
319 return "bool ";
320 if (!isSigned)
321 return "unsigned int"+utostr(NumBits)+" ";
322 return "int"+utostr(NumBits)+" ";
323 case Type::FloatTyID:
324 return "float32 ";
325 case Type::DoubleTyID:
326 return "float64 ";
327 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000328 errs() << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000329 llvm_unreachable("Invalid primitive type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000330 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000331 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000332}
333
334
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000335std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
336 bool isNested) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000337 if (Ty->isPrimitiveType() || Ty->isInteger())
338 return getPrimitiveTypeName(Ty,isSigned);
339 // FIXME: "OpaqueType" support
340 switch (Ty->getTypeID()) {
341 case Type::PointerTyID:
342 return "void* ";
343 case Type::StructTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000344 if (isNested)
345 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000346 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
347 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000348 if (isNested)
349 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000350 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
351 case Type::VectorTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000352 if (isNested)
353 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000354 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
355 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000356 errs() << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000357 llvm_unreachable("Invalid type in getTypeName()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000358 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000359 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000360}
361
362
363MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
364 // Function argument
365 if (isa<Argument>(V))
366 return ArgumentVT;
367 // Function
368 else if (const Function* F = dyn_cast<Function>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000369 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000370 // Variable
371 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000372 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000373 // Constant
374 else if (isa<Constant>(V))
375 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
376 // Local variable
377 return LocalVT;
378}
379
380
381std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
382 bool isSigned) {
383 unsigned NumBits = 0;
384 switch (Ty->getTypeID()) {
385 // Integer constant, expanding for stack operations.
386 case Type::IntegerTyID:
387 NumBits = getBitWidth(Ty);
388 // Expand integer value to "int32" or "int64".
389 if (Expand) return (NumBits<=32 ? "i4" : "i8");
390 if (NumBits==1) return "i1";
391 return (isSigned ? "i" : "u")+utostr(NumBits/8);
392 // Float constant.
393 case Type::FloatTyID:
394 return "r4";
395 case Type::DoubleTyID:
396 return "r8";
397 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +0000398 return "i"+utostr(TD->getTypeAllocSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000399 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000400 errs() << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000401 llvm_unreachable("Invalid type in TypeToPostfix()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000402 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000403 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000404}
405
406
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000407void MSILWriter::printConvToPtr() {
408 switch (ModulePtr->getPointerSize()) {
409 case Module::Pointer32:
410 printSimpleInstruction("conv.u4");
411 break;
412 case Module::Pointer64:
413 printSimpleInstruction("conv.u8");
414 break;
415 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000416 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000417 }
418}
419
420
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000421void MSILWriter::printPtrLoad(uint64_t N) {
422 switch (ModulePtr->getPointerSize()) {
423 case Module::Pointer32:
424 printSimpleInstruction("ldc.i4",utostr(N).c_str());
425 // FIXME: Need overflow test?
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000426 if (!isUInt32(N)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000427 errs() << "Value = " << utostr(N) << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000428 llvm_unreachable("32-bit pointer overflowed");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000429 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000430 break;
431 case Module::Pointer64:
432 printSimpleInstruction("ldc.i8",utostr(N).c_str());
433 break;
434 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000435 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000436 }
437}
438
439
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000440void MSILWriter::printValuePtrLoad(const Value* V) {
441 printValueLoad(V);
442 printConvToPtr();
443}
444
445
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000446void MSILWriter::printConstLoad(const Constant* C) {
447 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
448 // Integer constant
449 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
450 if (CInt->isMinValue(true))
451 Out << CInt->getSExtValue();
452 else
453 Out << CInt->getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000454 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000455 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000456 uint64_t X;
457 unsigned Size;
458 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000459 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000460 Size = 4;
461 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000462 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000463 Size = 8;
464 }
465 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
466 } else if (isa<UndefValue>(C)) {
467 // Undefined constant value = NULL.
468 printPtrLoad(0);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000469 } else {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000470 errs() << "Constant = " << *C << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000471 llvm_unreachable("Invalid constant value");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000472 }
473 Out << '\n';
474}
475
476
477void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000478 MSILWriter::ValueType Location = getValueLocation(V);
479 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000480 // Global variable or function address.
481 case GlobalVT:
482 case InternalVT:
483 if (const Function* F = dyn_cast<Function>(V)) {
484 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
485 printSimpleInstruction("ldftn",
486 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
487 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000488 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000489 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000490 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
491 Tmp = "void* "+getValueName(V);
492 printSimpleInstruction("ldsfld",Tmp.c_str());
493 } else {
494 Tmp = getTypeName(ElemTy)+getValueName(V);
495 printSimpleInstruction("ldsflda",Tmp.c_str());
496 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000497 }
498 break;
499 // Function argument.
500 case ArgumentVT:
501 printSimpleInstruction("ldarg",getValueName(V).c_str());
502 break;
503 // Local function variable.
504 case LocalVT:
505 printSimpleInstruction("ldloc",getValueName(V).c_str());
506 break;
507 // Constant value.
508 case ConstVT:
509 if (isa<ConstantPointerNull>(V))
510 printPtrLoad(0);
511 else
512 printConstLoad(cast<Constant>(V));
513 break;
514 // Constant expression.
515 case ConstExprVT:
516 printConstantExpr(cast<ConstantExpr>(V));
517 break;
518 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000519 errs() << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000520 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000521 }
522}
523
524
525void MSILWriter::printValueSave(const Value* V) {
526 switch (getValueLocation(V)) {
527 case ArgumentVT:
528 printSimpleInstruction("starg",getValueName(V).c_str());
529 break;
530 case LocalVT:
531 printSimpleInstruction("stloc",getValueName(V).c_str());
532 break;
533 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000534 errs() << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000535 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000536 }
537}
538
539
540void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
541 const Value* Right) {
542 printValueLoad(Left);
543 printValueLoad(Right);
544 Out << '\t' << Name << '\n';
545}
546
547
548void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
549 if(Operand)
550 Out << '\t' << Inst << '\t' << Operand << '\n';
551 else
552 Out << '\t' << Inst << '\n';
553}
554
555
556void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
Bill Wendling3ef10852009-12-28 01:42:12 +0000557 for (BasicBlock::const_iterator I = Dst->begin(); isa<PHINode>(I); ++I) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000558 const PHINode* Phi = cast<PHINode>(I);
559 const Value* Val = Phi->getIncomingValueForBlock(Src);
560 if (isa<UndefValue>(Val)) continue;
561 printValueLoad(Val);
562 printValueSave(Phi);
563 }
564}
565
566
567void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
568 const BasicBlock* TrueBB,
569 const BasicBlock* FalseBB) {
570 if (TrueBB==FalseBB) {
571 // "TrueBB" and "FalseBB" destination equals
572 printPHICopy(CurrBB,TrueBB);
573 printSimpleInstruction("pop");
574 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
575 } else if (FalseBB==NULL) {
576 // If "FalseBB" not used the jump have condition
577 printPHICopy(CurrBB,TrueBB);
578 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
579 } else if (TrueBB==NULL) {
580 // If "TrueBB" not used the jump is unconditional
581 printPHICopy(CurrBB,FalseBB);
582 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
583 } else {
584 // Copy PHI instructions for each block
585 std::string TmpLabel;
586 // Print PHI instructions for "TrueBB"
587 if (isa<PHINode>(TrueBB->begin())) {
588 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
589 printSimpleInstruction("brtrue",TmpLabel.c_str());
590 } else {
591 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
592 }
593 // Print PHI instructions for "FalseBB"
594 if (isa<PHINode>(FalseBB->begin())) {
595 printPHICopy(CurrBB,FalseBB);
596 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
597 } else {
598 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
599 }
600 if (isa<PHINode>(TrueBB->begin())) {
601 // Handle "TrueBB" PHI Copy
602 Out << TmpLabel << ":\n";
603 printPHICopy(CurrBB,TrueBB);
604 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
605 }
606 }
607}
608
609
610void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
611 if (Inst->isUnconditional()) {
612 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
613 } else {
614 printValueLoad(Inst->getCondition());
615 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
616 Inst->getSuccessor(1));
617 }
618}
619
620
621void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
622 const Value* VFalse) {
623 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
624 printValueLoad(VTrue);
625 printValueLoad(Cond);
626 printSimpleInstruction("brtrue",TmpLabel.c_str());
627 printSimpleInstruction("pop");
628 printValueLoad(VFalse);
629 Out << TmpLabel << ":\n";
630}
631
632
633void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000634 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000635 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000636 if (const PointerType* P = dyn_cast<PointerType>(Ty))
637 Ty = P->getElementType();
638 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000639 printSimpleInstruction(Tmp.c_str());
640}
641
642
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000643void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000644 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000645 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000646 printIndirectSave(Val->getType());
647}
648
649
650void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000651 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000652 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000653 if (*postfix.begin()=='u') *postfix.begin() = 'i';
654 postfix = "stind."+postfix;
655 printSimpleInstruction(postfix.c_str());
656}
657
658
659void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000660 const Type* Ty, const Type* SrcTy) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000661 std::string Tmp("");
662 printValueLoad(V);
663 switch (Op) {
664 // Signed
665 case Instruction::SExt:
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000666 // If sign extending int, convert first from unsigned to signed
667 // with the same bit size - because otherwise we will loose the sign.
668 if (SrcTy) {
669 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
670 printSimpleInstruction(Tmp.c_str());
671 }
Bill Wendling5f544502009-07-14 18:30:04 +0000672 // FALLTHROUGH
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000673 case Instruction::SIToFP:
674 case Instruction::FPToSI:
675 Tmp = "conv."+getTypePostfix(Ty,false,true);
676 printSimpleInstruction(Tmp.c_str());
677 break;
678 // Unsigned
679 case Instruction::FPTrunc:
680 case Instruction::FPExt:
681 case Instruction::UIToFP:
682 case Instruction::Trunc:
683 case Instruction::ZExt:
684 case Instruction::FPToUI:
685 case Instruction::PtrToInt:
686 case Instruction::IntToPtr:
687 Tmp = "conv."+getTypePostfix(Ty,false);
688 printSimpleInstruction(Tmp.c_str());
689 break;
690 // Do nothing
691 case Instruction::BitCast:
692 // FIXME: meaning that ld*/st* instruction do not change data format.
693 break;
694 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000695 errs() << "Opcode = " << Op << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000696 llvm_unreachable("Invalid conversion instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000697 }
698}
699
700
701void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
702 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000703 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000704 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000705 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000706 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000707 for (; I!=E; ++I){
708 Size = 0;
709 const Value* IndexValue = I.getOperand();
710 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
711 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
712 // Offset is the sum of all previous structure fields.
713 for (uint64_t F = 0; F<FieldIndex; ++F)
Duncan Sands777d2302009-05-09 07:06:46 +0000714 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000715 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000716 printSimpleInstruction("add");
717 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000718 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000719 Size = TD->getTypeAllocSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000720 } else {
Duncan Sands777d2302009-05-09 07:06:46 +0000721 Size = TD->getTypeAllocSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000722 }
723 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000724 if (!isZeroValue(IndexValue)) {
725 // Constant optimization.
726 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
727 if (C->getValue().isNegative()) {
728 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
729 printSimpleInstruction("sub");
730 continue;
731 } else
732 printPtrLoad(C->getZExtValue()*Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000733 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000734 printPtrLoad(Size);
735 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000736 printSimpleInstruction("mul");
737 }
738 printSimpleInstruction("add");
739 }
740 }
741}
742
743
744std::string MSILWriter::getCallSignature(const FunctionType* Ty,
745 const Instruction* Inst,
746 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000747 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000748 if (Ty->isVarArg()) Tmp += "vararg ";
749 // Name and return type.
750 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
751 // Function argument type list.
752 unsigned NumParams = Ty->getNumParams();
753 for (unsigned I = 0; I!=NumParams; ++I) {
754 if (I!=0) Tmp += ",";
755 Tmp += getTypeName(Ty->getParamType(I));
756 }
757 // CLR needs to know the exact amount of parameters received by vararg
758 // function, because caller cleans the stack.
759 if (Ty->isVarArg() && Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000760 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000761 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
762 // Print variable argument types.
763 unsigned NumOperands = Inst->getNumOperands()-Org;
764 if (NumParams<NumOperands) {
765 if (NumParams!=0) Tmp += ", ";
766 Tmp += "... , ";
767 for (unsigned J = NumParams; J!=NumOperands; ++J) {
768 if (J!=NumParams) Tmp += ", ";
769 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
770 }
771 }
772 }
773 return Tmp+")";
774}
775
776
777void MSILWriter::printFunctionCall(const Value* FnVal,
778 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000779 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000780 std::string Name = "";
781 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
782 Name = getConvModopt(Call->getCallingConv());
783 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
784 Name = getConvModopt(Invoke->getCallingConv());
785 else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000786 errs() << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000787 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000788 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000789 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000790 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000791 Name += getValueName(F);
792 printSimpleInstruction("call",
793 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
794 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000795 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000796 const PointerType* PTy = cast<PointerType>(FnVal->getType());
797 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000798 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000799 printValueLoad(FnVal);
800 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
801 }
802}
803
804
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000805void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
806 std::string Name;
807 switch (Inst->getIntrinsicID()) {
808 case Intrinsic::vastart:
809 Name = getValueName(Inst->getOperand(1));
810 Name.insert(Name.length()-1,"$valist");
811 // Obtain the argument handle.
812 printSimpleInstruction("ldloca",Name.c_str());
813 printSimpleInstruction("arglist");
814 printSimpleInstruction("call",
815 "instance void [mscorlib]System.ArgIterator::.ctor"
816 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
817 // Save as pointer type "void*"
818 printValueLoad(Inst->getOperand(1));
819 printSimpleInstruction("ldloca",Name.c_str());
Owen Anderson1d0be152009-08-13 21:58:54 +0000820 printIndirectSave(PointerType::getUnqual(
821 IntegerType::get(Inst->getContext(), 8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000822 break;
823 case Intrinsic::vaend:
824 // Close argument list handle.
825 printIndirectLoad(Inst->getOperand(1));
826 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
827 break;
828 case Intrinsic::vacopy:
829 // Copy "ArgIterator" valuetype.
830 printIndirectLoad(Inst->getOperand(1));
831 printIndirectLoad(Inst->getOperand(2));
832 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
833 break;
834 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000835 errs() << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000836 llvm_unreachable("Invalid intrinsic function");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000837 }
838}
839
840
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000841void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000842 if (isa<IntrinsicInst>(Inst)) {
843 // Handle intrinsic function.
844 printIntrinsicCall(cast<IntrinsicInst>(Inst));
845 } else {
846 // Load arguments to stack and call function.
847 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
848 printValueLoad(Inst->getOperand(I));
849 printFunctionCall(Inst->getOperand(0),Inst);
850 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000851}
852
853
854void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
855 const Value* Right) {
856 switch (Predicate) {
857 case ICmpInst::ICMP_EQ:
858 printBinaryInstruction("ceq",Left,Right);
859 break;
860 case ICmpInst::ICMP_NE:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000861 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000862 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000863 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000864 printSimpleInstruction("not");
865 break;
866 case ICmpInst::ICMP_ULE:
867 case ICmpInst::ICMP_SLE:
868 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
869 printBinaryInstruction("ceq",Left,Right);
870 if (Predicate==ICmpInst::ICMP_ULE)
871 printBinaryInstruction("clt.un",Left,Right);
872 else
873 printBinaryInstruction("clt",Left,Right);
874 printSimpleInstruction("or");
875 break;
876 case ICmpInst::ICMP_UGE:
877 case ICmpInst::ICMP_SGE:
878 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
879 printBinaryInstruction("ceq",Left,Right);
880 if (Predicate==ICmpInst::ICMP_UGE)
881 printBinaryInstruction("cgt.un",Left,Right);
882 else
883 printBinaryInstruction("cgt",Left,Right);
884 printSimpleInstruction("or");
885 break;
886 case ICmpInst::ICMP_ULT:
887 printBinaryInstruction("clt.un",Left,Right);
888 break;
889 case ICmpInst::ICMP_SLT:
890 printBinaryInstruction("clt",Left,Right);
891 break;
892 case ICmpInst::ICMP_UGT:
893 printBinaryInstruction("cgt.un",Left,Right);
Anton Korobeynikove9fd67e2009-07-14 09:52:47 +0000894 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000895 case ICmpInst::ICMP_SGT:
896 printBinaryInstruction("cgt",Left,Right);
897 break;
898 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000899 errs() << "Predicate = " << Predicate << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000900 llvm_unreachable("Invalid icmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000901 }
902}
903
904
905void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
906 const Value* Right) {
907 // FIXME: Correct comparison
908 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
909 switch (Predicate) {
910 case FCmpInst::FCMP_UGT:
911 // X > Y || llvm_fcmp_uno(X, Y)
912 printBinaryInstruction("cgt",Left,Right);
913 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
914 printSimpleInstruction("or");
915 break;
916 case FCmpInst::FCMP_OGT:
917 // X > Y
918 printBinaryInstruction("cgt",Left,Right);
919 break;
920 case FCmpInst::FCMP_UGE:
921 // X >= Y || llvm_fcmp_uno(X, Y)
922 printBinaryInstruction("ceq",Left,Right);
923 printBinaryInstruction("cgt",Left,Right);
924 printSimpleInstruction("or");
925 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
926 printSimpleInstruction("or");
927 break;
928 case FCmpInst::FCMP_OGE:
929 // X >= Y
930 printBinaryInstruction("ceq",Left,Right);
931 printBinaryInstruction("cgt",Left,Right);
932 printSimpleInstruction("or");
933 break;
934 case FCmpInst::FCMP_ULT:
935 // X < Y || llvm_fcmp_uno(X, Y)
936 printBinaryInstruction("clt",Left,Right);
937 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
938 printSimpleInstruction("or");
939 break;
940 case FCmpInst::FCMP_OLT:
941 // X < Y
942 printBinaryInstruction("clt",Left,Right);
943 break;
944 case FCmpInst::FCMP_ULE:
945 // X <= Y || llvm_fcmp_uno(X, Y)
946 printBinaryInstruction("ceq",Left,Right);
947 printBinaryInstruction("clt",Left,Right);
948 printSimpleInstruction("or");
949 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
950 printSimpleInstruction("or");
951 break;
952 case FCmpInst::FCMP_OLE:
953 // X <= Y
954 printBinaryInstruction("ceq",Left,Right);
955 printBinaryInstruction("clt",Left,Right);
956 printSimpleInstruction("or");
957 break;
958 case FCmpInst::FCMP_UEQ:
959 // X == Y || llvm_fcmp_uno(X, Y)
960 printBinaryInstruction("ceq",Left,Right);
961 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
962 printSimpleInstruction("or");
963 break;
964 case FCmpInst::FCMP_OEQ:
965 // X == Y
966 printBinaryInstruction("ceq",Left,Right);
967 break;
968 case FCmpInst::FCMP_UNE:
969 // X != Y
970 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000971 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000972 printSimpleInstruction("not");
973 break;
974 case FCmpInst::FCMP_ONE:
975 // X != Y && llvm_fcmp_ord(X, Y)
976 printBinaryInstruction("ceq",Left,Right);
977 printSimpleInstruction("not");
978 break;
979 case FCmpInst::FCMP_ORD:
980 // return X == X && Y == Y
981 printBinaryInstruction("ceq",Left,Left);
982 printBinaryInstruction("ceq",Right,Right);
983 printSimpleInstruction("or");
984 break;
985 case FCmpInst::FCMP_UNO:
986 // X != X || Y != Y
987 printBinaryInstruction("ceq",Left,Left);
988 printSimpleInstruction("not");
989 printBinaryInstruction("ceq",Right,Right);
990 printSimpleInstruction("not");
991 printSimpleInstruction("or");
992 break;
993 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000994 llvm_unreachable("Illegal FCmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000995 }
996}
997
998
999void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1000 std::string Label = "leave$normal_"+utostr(getUniqID());
1001 Out << ".try {\n";
1002 // Load arguments
1003 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1004 printValueLoad(Inst->getOperand(I));
1005 // Print call instruction
1006 printFunctionCall(Inst->getOperand(0),Inst);
1007 // Save function result and leave "try" block
1008 printValueSave(Inst);
1009 printSimpleInstruction("leave",Label.c_str());
1010 Out << "}\n";
1011 Out << "catch [mscorlib]System.Exception {\n";
1012 // Redirect to unwind block
1013 printSimpleInstruction("pop");
1014 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1015 Out << "}\n" << Label << ":\n";
1016 // Redirect to continue block
1017 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1018}
1019
1020
1021void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1022 // FIXME: Emulate with IL "switch" instruction
1023 // Emulate = if () else if () else if () else ...
1024 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1025 printValueLoad(Inst->getCondition());
1026 printValueLoad(Inst->getCaseValue(I));
1027 printSimpleInstruction("ceq");
1028 // Condition jump to successor block
1029 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1030 }
1031 // Jump to default block
1032 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1033}
1034
1035
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001036void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1037 printIndirectLoad(Inst->getOperand(0));
1038 printSimpleInstruction("call",
1039 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1040 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001041 std::string Name =
Owen Anderson1d0be152009-08-13 21:58:54 +00001042 "ldind."+getTypePostfix(PointerType::getUnqual(
1043 IntegerType::get(Inst->getContext(), 8)),false);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001044 printSimpleInstruction(Name.c_str());
1045}
1046
1047
1048void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
Duncan Sands777d2302009-05-09 07:06:46 +00001049 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001050 // Constant optimization.
1051 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1052 printPtrLoad(CInt->getZExtValue()*Size);
1053 } else {
1054 printPtrLoad(Size);
1055 printValueLoad(Inst->getOperand(0));
1056 printSimpleInstruction("mul");
1057 }
1058 printSimpleInstruction("localloc");
1059}
1060
1061
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001062void MSILWriter::printInstruction(const Instruction* Inst) {
1063 const Value *Left = 0, *Right = 0;
1064 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1065 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1066 // Print instruction
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001067 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001068 switch (Inst->getOpcode()) {
1069 // Terminator
1070 case Instruction::Ret:
1071 if (Inst->getNumOperands()) {
1072 printValueLoad(Left);
1073 printSimpleInstruction("ret");
1074 } else
1075 printSimpleInstruction("ret");
1076 break;
1077 case Instruction::Br:
1078 printBranchInstruction(cast<BranchInst>(Inst));
1079 break;
1080 // Binary
1081 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001082 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001083 printBinaryInstruction("add",Left,Right);
1084 break;
1085 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001086 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001087 printBinaryInstruction("sub",Left,Right);
1088 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001089 case Instruction::Mul:
1090 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001091 printBinaryInstruction("mul",Left,Right);
1092 break;
1093 case Instruction::UDiv:
1094 printBinaryInstruction("div.un",Left,Right);
1095 break;
1096 case Instruction::SDiv:
1097 case Instruction::FDiv:
1098 printBinaryInstruction("div",Left,Right);
1099 break;
1100 case Instruction::URem:
1101 printBinaryInstruction("rem.un",Left,Right);
1102 break;
1103 case Instruction::SRem:
1104 case Instruction::FRem:
1105 printBinaryInstruction("rem",Left,Right);
1106 break;
1107 // Binary Condition
1108 case Instruction::ICmp:
1109 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1110 break;
1111 case Instruction::FCmp:
1112 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1113 break;
1114 // Bitwise Binary
1115 case Instruction::And:
1116 printBinaryInstruction("and",Left,Right);
1117 break;
1118 case Instruction::Or:
1119 printBinaryInstruction("or",Left,Right);
1120 break;
1121 case Instruction::Xor:
1122 printBinaryInstruction("xor",Left,Right);
1123 break;
1124 case Instruction::Shl:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001125 printValueLoad(Left);
1126 printValueLoad(Right);
1127 printSimpleInstruction("conv.i4");
1128 printSimpleInstruction("shl");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001129 break;
1130 case Instruction::LShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001131 printValueLoad(Left);
1132 printValueLoad(Right);
1133 printSimpleInstruction("conv.i4");
1134 printSimpleInstruction("shr.un");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001135 break;
1136 case Instruction::AShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001137 printValueLoad(Left);
1138 printValueLoad(Right);
1139 printSimpleInstruction("conv.i4");
1140 printSimpleInstruction("shr");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001141 break;
1142 case Instruction::Select:
1143 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1144 break;
1145 case Instruction::Load:
1146 printIndirectLoad(Inst->getOperand(0));
1147 break;
1148 case Instruction::Store:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001149 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001150 break;
Anton Korobeynikov94ac0342009-07-14 09:53:14 +00001151 case Instruction::SExt:
1152 printCastInstruction(Inst->getOpcode(),Left,
1153 cast<CastInst>(Inst)->getDestTy(),
1154 cast<CastInst>(Inst)->getSrcTy());
1155 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001156 case Instruction::Trunc:
1157 case Instruction::ZExt:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001158 case Instruction::FPTrunc:
1159 case Instruction::FPExt:
1160 case Instruction::UIToFP:
1161 case Instruction::SIToFP:
1162 case Instruction::FPToUI:
1163 case Instruction::FPToSI:
1164 case Instruction::PtrToInt:
1165 case Instruction::IntToPtr:
1166 case Instruction::BitCast:
1167 printCastInstruction(Inst->getOpcode(),Left,
1168 cast<CastInst>(Inst)->getDestTy());
1169 break;
1170 case Instruction::GetElementPtr:
1171 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1172 gep_type_end(Inst));
1173 break;
1174 case Instruction::Call:
1175 printCallInstruction(cast<CallInst>(Inst));
1176 break;
1177 case Instruction::Invoke:
1178 printInvokeInstruction(cast<InvokeInst>(Inst));
1179 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001180 case Instruction::Unwind:
1181 printSimpleInstruction("newobj",
1182 "instance void [mscorlib]System.Exception::.ctor()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001183 printSimpleInstruction("throw");
1184 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001185 case Instruction::Switch:
1186 printSwitchInstruction(cast<SwitchInst>(Inst));
1187 break;
1188 case Instruction::Alloca:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001189 printAllocaInstruction(cast<AllocaInst>(Inst));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001190 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001191 case Instruction::Unreachable:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001192 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1193 printSimpleInstruction("newobj",
1194 "instance void [mscorlib]System.Exception::.ctor(string)");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001195 printSimpleInstruction("throw");
1196 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001197 case Instruction::VAArg:
1198 printVAArgInstruction(cast<VAArgInst>(Inst));
1199 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001200 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001201 errs() << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001202 llvm_unreachable("Unsupported instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001203 }
1204}
1205
1206
1207void MSILWriter::printLoop(const Loop* L) {
1208 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1209 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1210 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1211 BasicBlock* BB = blocks[I];
1212 Loop* BBLoop = LInfo->getLoopFor(BB);
1213 if (BBLoop == L)
1214 printBasicBlock(BB);
1215 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1216 printLoop(BBLoop);
1217 }
1218 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1219}
1220
1221
1222void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1223 Out << getLabelName(BB) << ":\n";
1224 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1225 const Instruction* Inst = I;
1226 // Comment llvm original instruction
Owen Andersoncb371882008-08-21 00:14:44 +00001227 // Out << "\n//" << *Inst << "\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001228 // Do not handle PHI instruction in current block
1229 if (Inst->getOpcode()==Instruction::PHI) continue;
1230 // Print instruction
1231 printInstruction(Inst);
1232 // Save result
Owen Anderson1d0be152009-08-13 21:58:54 +00001233 if (Inst->getType()!=Type::getVoidTy(BB->getContext())) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001234 // Do not save value after invoke, it done in "try" block
1235 if (Inst->getOpcode()==Instruction::Invoke) continue;
1236 printValueSave(Inst);
1237 }
1238 }
1239}
1240
1241
1242void MSILWriter::printLocalVariables(const Function& F) {
1243 std::string Name;
1244 const Type* Ty = NULL;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001245 std::set<const Value*> Printed;
1246 const Value* VaList = NULL;
1247 unsigned StackDepth = 8;
1248 // Find local variables
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001249 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001250 if (I->getOpcode()==Instruction::Call ||
1251 I->getOpcode()==Instruction::Invoke) {
1252 // Test stack depth.
1253 if (StackDepth<I->getNumOperands())
1254 StackDepth = I->getNumOperands();
1255 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001256 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1257 if (AI && !isa<GlobalVariable>(AI)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001258 // Local variable allocation.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001259 Ty = PointerType::getUnqual(AI->getAllocatedType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001260 Name = getValueName(AI);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001261 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00001262 } else if (I->getType()!=Type::getVoidTy(F.getContext())) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001263 // Operation result.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001264 Ty = I->getType();
1265 Name = getValueName(&*I);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001266 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1267 }
1268 // Test on 'va_list' variable
1269 bool isVaList = false;
1270 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1271 // "va_list" as "va_arg" instruction operand.
1272 isVaList = true;
1273 VaList = VaInst->getOperand(0);
1274 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1275 // "va_list" as intrinsic function operand.
1276 switch (Inst->getIntrinsicID()) {
1277 case Intrinsic::vastart:
1278 case Intrinsic::vaend:
1279 case Intrinsic::vacopy:
1280 isVaList = true;
1281 VaList = Inst->getOperand(1);
1282 break;
1283 default:
1284 isVaList = false;
1285 }
1286 }
1287 // Print "va_list" variable.
1288 if (isVaList && Printed.insert(VaList).second) {
1289 Name = getValueName(VaList);
1290 Name.insert(Name.length()-1,"$valist");
1291 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1292 << Name << ")\n";
1293 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001294 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001295 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001296}
1297
1298
1299void MSILWriter::printFunctionBody(const Function& F) {
1300 // Print body
1301 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1302 if (Loop *L = LInfo->getLoopFor(I)) {
1303 if (L->getHeader()==I && L->getParentLoop()==0)
1304 printLoop(L);
1305 } else {
1306 printBasicBlock(I);
1307 }
1308 }
1309}
1310
1311
1312void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1313 const Value *left = 0, *right = 0;
1314 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1315 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1316 // Print instruction
1317 switch (CE->getOpcode()) {
1318 case Instruction::Trunc:
1319 case Instruction::ZExt:
1320 case Instruction::SExt:
1321 case Instruction::FPTrunc:
1322 case Instruction::FPExt:
1323 case Instruction::UIToFP:
1324 case Instruction::SIToFP:
1325 case Instruction::FPToUI:
1326 case Instruction::FPToSI:
1327 case Instruction::PtrToInt:
1328 case Instruction::IntToPtr:
1329 case Instruction::BitCast:
1330 printCastInstruction(CE->getOpcode(),left,CE->getType());
1331 break;
1332 case Instruction::GetElementPtr:
1333 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1334 break;
1335 case Instruction::ICmp:
1336 printICmpInstruction(CE->getPredicate(),left,right);
1337 break;
1338 case Instruction::FCmp:
1339 printFCmpInstruction(CE->getPredicate(),left,right);
1340 break;
1341 case Instruction::Select:
1342 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1343 break;
1344 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001345 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001346 printBinaryInstruction("add",left,right);
1347 break;
1348 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001349 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001350 printBinaryInstruction("sub",left,right);
1351 break;
1352 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001353 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001354 printBinaryInstruction("mul",left,right);
1355 break;
1356 case Instruction::UDiv:
1357 printBinaryInstruction("div.un",left,right);
1358 break;
1359 case Instruction::SDiv:
1360 case Instruction::FDiv:
1361 printBinaryInstruction("div",left,right);
1362 break;
1363 case Instruction::URem:
1364 printBinaryInstruction("rem.un",left,right);
1365 break;
1366 case Instruction::SRem:
1367 case Instruction::FRem:
1368 printBinaryInstruction("rem",left,right);
1369 break;
1370 case Instruction::And:
1371 printBinaryInstruction("and",left,right);
1372 break;
1373 case Instruction::Or:
1374 printBinaryInstruction("or",left,right);
1375 break;
1376 case Instruction::Xor:
1377 printBinaryInstruction("xor",left,right);
1378 break;
1379 case Instruction::Shl:
1380 printBinaryInstruction("shl",left,right);
1381 break;
1382 case Instruction::LShr:
1383 printBinaryInstruction("shr.un",left,right);
1384 break;
1385 case Instruction::AShr:
1386 printBinaryInstruction("shr",left,right);
1387 break;
1388 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001389 errs() << "Expression = " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001390 llvm_unreachable("Invalid constant expression");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001391 }
1392}
1393
1394
1395void MSILWriter::printStaticInitializerList() {
1396 // List of global variables with uninitialized fields.
1397 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1398 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1399 ++VarI) {
1400 const std::vector<StaticInitializer>& InitList = VarI->second;
1401 if (InitList.empty()) continue;
1402 // For each uninitialized field.
1403 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1404 E = InitList.end(); I!=E; ++I) {
1405 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
Owen Andersoncb371882008-08-21 00:14:44 +00001406 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1407 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001408 // Load variable address
1409 printValueLoad(VarI->first);
1410 // Add offset
1411 if (I->offset!=0) {
1412 printPtrLoad(I->offset);
1413 printSimpleInstruction("add");
1414 }
1415 // Load value
1416 printConstantExpr(CE);
1417 // Save result at offset
1418 std::string postfix = getTypePostfix(CE->getType(),true);
1419 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1420 postfix = "stind."+postfix;
1421 printSimpleInstruction(postfix.c_str());
1422 } else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001423 errs() << "Constant = " << *I->constant << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001424 llvm_unreachable("Invalid static initializer");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001425 }
1426 }
1427 }
1428}
1429
1430
1431void MSILWriter::printFunction(const Function& F) {
Devang Patel05988662008-09-25 21:00:45 +00001432 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001433 Out << "\n.method static ";
Rafael Espindolabb46f522009-01-15 20:18:42 +00001434 Out << (F.hasLocalLinkage() ? "private " : "public ");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001435 if (F.isVarArg()) Out << "vararg ";
1436 Out << getTypeName(F.getReturnType(),isSigned) <<
1437 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1438 // Arguments
1439 Out << "\t(";
1440 unsigned ArgIdx = 1;
1441 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1442 ++I, ++ArgIdx) {
Devang Patel05988662008-09-25 21:00:45 +00001443 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001444 if (I!=F.arg_begin()) Out << ", ";
1445 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1446 }
1447 Out << ") cil managed\n";
1448 // Body
1449 Out << "{\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001450 printLocalVariables(F);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001451 printFunctionBody(F);
1452 Out << "}\n";
1453}
1454
1455
1456void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1457 std::string Name;
1458 std::set<const Type*> Printed;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001459 for (std::set<const Type*>::const_iterator
1460 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1461 const Type* Ty = *UI;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001462 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1463 Name = getTypeName(Ty, false, true);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001464 // Type with no need to declare.
1465 else continue;
1466 // Print not duplicated type
1467 if (Printed.insert(Ty).second) {
1468 Out << ".class value explicit ansi sealed '" << Name << "'";
Duncan Sands777d2302009-05-09 07:06:46 +00001469 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001470 Out << " }\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001471 }
1472 }
1473}
1474
1475
1476unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1477 unsigned int N = Ty->getPrimitiveSizeInBits();
1478 assert(N!=0 && "Invalid type in getBitWidth()");
1479 switch (N) {
1480 case 1:
1481 case 8:
1482 case 16:
1483 case 32:
1484 case 64:
1485 return N;
1486 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001487 errs() << "Bits = " << N << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001488 llvm_unreachable("Unsupported integer width");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001489 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001490 return 0; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001491}
1492
1493
1494void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1495 uint64_t TySize = 0;
1496 const Type* Ty = C->getType();
1497 // Print zero initialized constant.
1498 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
Duncan Sands777d2302009-05-09 07:06:46 +00001499 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001500 Offset += TySize;
1501 Out << "int8 (0) [" << TySize << "]";
1502 return;
1503 }
1504 // Print constant initializer
1505 switch (Ty->getTypeID()) {
1506 case Type::IntegerTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001507 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001508 const ConstantInt* Int = cast<ConstantInt>(C);
1509 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1510 break;
1511 }
1512 case Type::FloatTyID:
1513 case Type::DoubleTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001514 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001515 const ConstantFP* FP = cast<ConstantFP>(C);
1516 if (Ty->getTypeID() == Type::FloatTyID)
Dale Johannesen43421b32007-09-06 18:13:44 +00001517 Out << "int32 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001518 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001519 else
Dale Johannesen43421b32007-09-06 18:13:44 +00001520 Out << "int64 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001521 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001522 break;
1523 }
1524 case Type::ArrayTyID:
1525 case Type::VectorTyID:
1526 case Type::StructTyID:
1527 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1528 if (I!=0) Out << ",\n";
Chris Lattner0eeb9132009-10-28 05:14:34 +00001529 printStaticConstant(cast<Constant>(C->getOperand(I)), Offset);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001530 }
1531 break;
1532 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +00001533 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001534 // Initialize with global variable address
1535 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1536 std::string name = getValueName(G);
1537 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1538 } else {
1539 // Dynamic initialization
1540 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1541 InitListPtr->push_back(StaticInitializer(C,Offset));
1542 // Null pointer initialization
1543 if (TySize==4) Out << "int32 (0)";
1544 else if (TySize==8) Out << "int64 (0)";
Torok Edwinc23197a2009-07-14 16:55:14 +00001545 else llvm_unreachable("Invalid pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001546 }
1547 break;
1548 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001549 errs() << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001550 llvm_unreachable("Invalid type in printStaticConstant()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001551 }
1552 // Increase offset.
1553 Offset += TySize;
1554}
1555
1556
1557void MSILWriter::printStaticInitializer(const Constant* C,
1558 const std::string& Name) {
1559 switch (C->getType()->getTypeID()) {
1560 case Type::IntegerTyID:
1561 case Type::FloatTyID:
1562 case Type::DoubleTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001563 Out << getPrimitiveTypeName(C->getType(), false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001564 break;
1565 case Type::ArrayTyID:
1566 case Type::VectorTyID:
1567 case Type::StructTyID:
1568 case Type::PointerTyID:
1569 Out << getTypeName(C->getType());
1570 break;
1571 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001572 errs() << "Type = " << *C << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001573 llvm_unreachable("Invalid constant type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001574 }
1575 // Print initializer
1576 std::string label = Name;
1577 label.insert(label.length()-1,"$data");
1578 Out << Name << " at " << label << '\n';
1579 Out << ".data " << label << " = {\n";
1580 uint64_t offset = 0;
1581 printStaticConstant(C,offset);
1582 Out << "\n}\n\n";
1583}
1584
1585
1586void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1587 const Constant* C = G->getInitializer();
1588 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1589 InitListPtr = 0;
1590 else
1591 InitListPtr = &StaticInitList[G];
1592 printStaticInitializer(C,getValueName(G));
1593}
1594
1595
1596void MSILWriter::printGlobalVariables() {
1597 if (ModulePtr->global_empty()) return;
1598 Module::global_iterator I,E;
1599 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1600 // Variable definition
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001601 Out << ".field static " << (I->isDeclaration() ? "public " :
1602 "private ");
1603 if (I->isDeclaration()) {
1604 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1605 } else
1606 printVariableDefinition(&*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001607 }
1608}
1609
1610
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001611const char* MSILWriter::getLibraryName(const Function* F) {
Daniel Dunbarbda96532009-07-21 08:57:31 +00001612 return getLibraryForSymbol(F->getName(), true, F->getCallingConv());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001613}
1614
1615
1616const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
Chris Lattner27891032010-01-16 02:15:38 +00001617 return getLibraryForSymbol(GV->getName(), false, CallingConv::C);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001618}
1619
1620
Daniel Dunbarbda96532009-07-21 08:57:31 +00001621const char* MSILWriter::getLibraryForSymbol(const StringRef &Name,
1622 bool isFunction,
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001623 CallingConv::ID CallingConv) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001624 // TODO: Read *.def file with function and libraries definitions.
1625 return "MSVCRT.DLL";
1626}
1627
1628
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001629void MSILWriter::printExternals() {
1630 Module::const_iterator I,E;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001631 // Functions.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001632 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1633 // Skip intrisics
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001634 if (I->isIntrinsic()) continue;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001635 if (I->isDeclaration()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001636 const Function* F = I;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001637 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001638 std::string Sig =
1639 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1640 Out << ".method static hidebysig pinvokeimpl(\""
1641 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001642 }
1643 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001644 // External variables and static initialization.
1645 Out <<
1646 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1647 " native int LoadLibrary(string) preservesig {}\n"
1648 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1649 " native int GetProcAddress(native int, string) preservesig {}\n";
1650 Out <<
1651 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1652 " managed cil\n{\n"
1653 "\tldarg\tlib\n"
1654 "\tcall\tnative int LoadLibrary(string)\n"
1655 "\tldarg\tsym\n"
1656 "\tcall\tnative int GetProcAddress(native int,string)\n"
1657 "\tdup\n"
1658 "\tbrtrue\tL_01\n"
1659 "\tldstr\t\"Can no import variable\"\n"
1660 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1661 "\tthrow\n"
1662 "L_01:\n"
1663 "\tret\n"
1664 "}\n\n"
1665 ".method static private void $MSIL_Init() managed cil\n{\n";
1666 printStaticInitializerList();
1667 // Foreach global variable.
1668 for (Module::global_iterator I = ModulePtr->global_begin(),
1669 E = ModulePtr->global_end(); I!=E; ++I) {
1670 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1671 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001672 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1673 printSimpleInstruction("ldsflda",Tmp.c_str());
1674 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
Chris Lattner27891032010-01-16 02:15:38 +00001675 Out << "\tldstr\t\"" << I->getName() << "\"\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001676 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1677 printIndirectSave(I->getType());
1678 }
1679 printSimpleInstruction("ret");
1680 Out << "}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001681}
1682
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001683
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001684//===----------------------------------------------------------------------===//
Bill Wendling85db3a92008-02-26 10:57:23 +00001685// External Interface declaration
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001686//===----------------------------------------------------------------------===//
1687
David Greene71847812009-07-14 20:18:05 +00001688bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1689 formatted_raw_ostream &o,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001690 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00001691 CodeGenOpt::Level OptLevel)
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001692{
1693 if (FileType != TargetMachine::AssemblyFile) return true;
1694 MSILWriter* Writer = new MSILWriter(o);
Gordon Henriksence224772008-01-07 01:30:38 +00001695 PM.add(createGCLoweringPass());
Eric Christopher5e639902009-12-18 02:12:53 +00001696 // FIXME: Handle switch through native IL instruction "switch"
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001697 PM.add(createLowerSwitchPass());
1698 PM.add(createCFGSimplificationPass());
1699 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1700 PM.add(Writer);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001701 PM.add(createGCInfoDeleter());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001702 return false;
1703}