Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(611)

Side by Side Diff: src/llvm2ice.cpp

Issue 350933002: Refactor llvm2ice so that Ice can be built while reading bitcode. (Closed) Base URL: https://chromium.googlesource.com/native_client/pnacl-subzero.git@master
Patch Set: Fix nits in patch set 2. Created 6 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « src/IceIntrinsics.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 //===- subzero/src/llvm2ice.cpp - Driver for testing ----------------------===// 1 //===- subzero/src/llvm2ice.cpp - Driver for testing ----------------------===//
2 // 2 //
3 // The Subzero Code Generator 3 // The Subzero Code Generator
4 // 4 //
5 // This file is distributed under the University of Illinois Open Source 5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details. 6 // License. See LICENSE.TXT for details.
7 // 7 //
8 //===----------------------------------------------------------------------===// 8 //===----------------------------------------------------------------------===//
9 // 9 //
10 // This file defines a driver that uses LLVM capabilities to parse a 10 // This file defines a driver that uses LLVM capabilities to parse a
11 // bitcode file and build the LLVM IR, and then convert the LLVM basic 11 // bitcode file and build the LLVM IR, and then convert the LLVM basic
12 // blocks, instructions, and operands into their Subzero equivalents. 12 // blocks, instructions, and operands into their Subzero equivalents.
13 // 13 //
14 //===----------------------------------------------------------------------===// 14 //===----------------------------------------------------------------------===//
15 15
16 #include "IceCfg.h" 16 #include "IceConverter.h"
17 #include "IceCfgNode.h"
18 #include "IceDefs.h" 17 #include "IceDefs.h"
19 #include "IceGlobalContext.h"
20 #include "IceInst.h"
21 #include "IceOperand.h"
22 #include "IceTargetLowering.h"
23 #include "IceTypes.h" 18 #include "IceTypes.h"
24 19
25 #include "llvm/IR/Constant.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Instruction.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/LLVMContext.h" 20 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IRReader/IRReader.h" 21 #include "llvm/IRReader/IRReader.h"
33 #include "llvm/Support/CommandLine.h" 22 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_os_ostream.h" 23 #include "llvm/Support/raw_os_ostream.h"
36 #include "llvm/Support/SourceMgr.h" 24 #include "llvm/Support/SourceMgr.h"
37 25
38 #include <fstream> 26 #include <fstream>
39 #include <iostream> 27 #include <iostream>
40 28
41 using namespace llvm; 29 using namespace llvm;
42 30
43 // Debugging helper
44 template <typename T> static std::string LLVMObjectAsString(const T *O) {
45 std::string Dump;
46 raw_string_ostream Stream(Dump);
47 O->print(Stream);
48 return Stream.str();
49 }
50
51 // Converter from LLVM to ICE. The entry point is the convertFunction method.
52 //
53 // Note: this currently assumes that the given IR was verified to be valid PNaCl
54 // bitcode:
55 // https://developers.google.com/native-client/dev/reference/pnacl-bitcode-abi
56 // If not, all kinds of assertions may fire.
57 //
58 class LLVM2ICEConverter {
59 public:
60 LLVM2ICEConverter(Ice::GlobalContext *Ctx)
61 : Ctx(Ctx), Func(NULL), CurrentNode(NULL) {
62 // All PNaCl pointer widths are 32 bits because of the sandbox
63 // model.
64 SubzeroPointerType = Ice::IceType_i32;
65 }
66
67 // Caller is expected to delete the returned Ice::Cfg object.
68 Ice::Cfg *convertFunction(const Function *F) {
69 VarMap.clear();
70 NodeMap.clear();
71 Func = new Ice::Cfg(Ctx);
72 Func->setFunctionName(F->getName());
73 Func->setReturnType(convertType(F->getReturnType()));
74 Func->setInternal(F->hasInternalLinkage());
75
76 // The initial definition/use of each arg is the entry node.
77 CurrentNode = mapBasicBlockToNode(&F->getEntryBlock());
78 for (Function::const_arg_iterator ArgI = F->arg_begin(),
79 ArgE = F->arg_end();
80 ArgI != ArgE; ++ArgI) {
81 Func->addArg(mapValueToIceVar(ArgI));
82 }
83
84 // Make an initial pass through the block list just to resolve the
85 // blocks in the original linearized order. Otherwise the ICE
86 // linearized order will be affected by branch targets in
87 // terminator instructions.
88 for (Function::const_iterator BBI = F->begin(), BBE = F->end(); BBI != BBE;
89 ++BBI) {
90 mapBasicBlockToNode(BBI);
91 }
92 for (Function::const_iterator BBI = F->begin(), BBE = F->end(); BBI != BBE;
93 ++BBI) {
94 CurrentNode = mapBasicBlockToNode(BBI);
95 convertBasicBlock(BBI);
96 }
97 Func->setEntryNode(mapBasicBlockToNode(&F->getEntryBlock()));
98 Func->computePredecessors();
99
100 return Func;
101 }
102
103 // convertConstant() does not use Func or require it to be a valid
104 // Ice::Cfg pointer. As such, it's suitable for e.g. constructing
105 // global initializers.
106 Ice::Constant *convertConstant(const Constant *Const) {
107 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Const)) {
108 return Ctx->getConstantSym(convertType(GV->getType()), 0, GV->getName());
109 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Const)) {
110 return Ctx->getConstantInt(convertIntegerType(CI->getType()),
111 CI->getZExtValue());
112 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Const)) {
113 Ice::Type Type = convertType(CFP->getType());
114 if (Type == Ice::IceType_f32)
115 return Ctx->getConstantFloat(CFP->getValueAPF().convertToFloat());
116 else if (Type == Ice::IceType_f64)
117 return Ctx->getConstantDouble(CFP->getValueAPF().convertToDouble());
118 llvm_unreachable("Unexpected floating point type");
119 return NULL;
120 } else if (const UndefValue *CU = dyn_cast<UndefValue>(Const)) {
121 return Ctx->getConstantUndef(convertType(CU->getType()));
122 } else {
123 llvm_unreachable("Unhandled constant type");
124 return NULL;
125 }
126 }
127
128 private:
129 // LLVM values (instructions, etc.) are mapped directly to ICE variables.
130 // mapValueToIceVar has a version that forces an ICE type on the variable,
131 // and a version that just uses convertType on V.
132 Ice::Variable *mapValueToIceVar(const Value *V, Ice::Type IceTy) {
133 if (IceTy == Ice::IceType_void)
134 return NULL;
135 if (VarMap.find(V) == VarMap.end()) {
136 assert(CurrentNode);
137 VarMap[V] = Func->makeVariable(IceTy, CurrentNode, V->getName());
138 }
139 return VarMap[V];
140 }
141
142 Ice::Variable *mapValueToIceVar(const Value *V) {
143 return mapValueToIceVar(V, convertType(V->getType()));
144 }
145
146 Ice::CfgNode *mapBasicBlockToNode(const BasicBlock *BB) {
147 if (NodeMap.find(BB) == NodeMap.end()) {
148 NodeMap[BB] = Func->makeNode(BB->getName());
149 }
150 return NodeMap[BB];
151 }
152
153 Ice::Type convertIntegerType(const IntegerType *IntTy) const {
154 switch (IntTy->getBitWidth()) {
155 case 1:
156 return Ice::IceType_i1;
157 case 8:
158 return Ice::IceType_i8;
159 case 16:
160 return Ice::IceType_i16;
161 case 32:
162 return Ice::IceType_i32;
163 case 64:
164 return Ice::IceType_i64;
165 default:
166 report_fatal_error(std::string("Invalid PNaCl int type: ") +
167 LLVMObjectAsString(IntTy));
168 return Ice::IceType_void;
169 }
170 }
171
172 Ice::Type convertType(const Type *Ty) const {
173 switch (Ty->getTypeID()) {
174 case Type::VoidTyID:
175 return Ice::IceType_void;
176 case Type::IntegerTyID:
177 return convertIntegerType(cast<IntegerType>(Ty));
178 case Type::FloatTyID:
179 return Ice::IceType_f32;
180 case Type::DoubleTyID:
181 return Ice::IceType_f64;
182 case Type::PointerTyID:
183 return SubzeroPointerType;
184 case Type::FunctionTyID:
185 return SubzeroPointerType;
186 default:
187 report_fatal_error(std::string("Invalid PNaCl type: ") +
188 LLVMObjectAsString(Ty));
189 }
190
191 llvm_unreachable("convertType");
192 return Ice::IceType_void;
193 }
194
195 // Given an LLVM instruction and an operand number, produce the
196 // Ice::Operand this refers to. If there's no such operand, return
197 // NULL.
198 Ice::Operand *convertOperand(const Instruction *Inst, unsigned OpNum) {
199 if (OpNum >= Inst->getNumOperands()) {
200 return NULL;
201 }
202 const Value *Op = Inst->getOperand(OpNum);
203 return convertValue(Op);
204 }
205
206 Ice::Operand *convertValue(const Value *Op) {
207 if (const Constant *Const = dyn_cast<Constant>(Op)) {
208 return convertConstant(Const);
209 } else {
210 return mapValueToIceVar(Op);
211 }
212 }
213
214 // Note: this currently assumes a 1x1 mapping between LLVM IR and Ice
215 // instructions.
216 Ice::Inst *convertInstruction(const Instruction *Inst) {
217 switch (Inst->getOpcode()) {
218 case Instruction::PHI:
219 return convertPHINodeInstruction(cast<PHINode>(Inst));
220 case Instruction::Br:
221 return convertBrInstruction(cast<BranchInst>(Inst));
222 case Instruction::Ret:
223 return convertRetInstruction(cast<ReturnInst>(Inst));
224 case Instruction::IntToPtr:
225 return convertIntToPtrInstruction(cast<IntToPtrInst>(Inst));
226 case Instruction::PtrToInt:
227 return convertPtrToIntInstruction(cast<PtrToIntInst>(Inst));
228 case Instruction::ICmp:
229 return convertICmpInstruction(cast<ICmpInst>(Inst));
230 case Instruction::FCmp:
231 return convertFCmpInstruction(cast<FCmpInst>(Inst));
232 case Instruction::Select:
233 return convertSelectInstruction(cast<SelectInst>(Inst));
234 case Instruction::Switch:
235 return convertSwitchInstruction(cast<SwitchInst>(Inst));
236 case Instruction::Load:
237 return convertLoadInstruction(cast<LoadInst>(Inst));
238 case Instruction::Store:
239 return convertStoreInstruction(cast<StoreInst>(Inst));
240 case Instruction::ZExt:
241 return convertCastInstruction(cast<ZExtInst>(Inst), Ice::InstCast::Zext);
242 case Instruction::SExt:
243 return convertCastInstruction(cast<SExtInst>(Inst), Ice::InstCast::Sext);
244 case Instruction::Trunc:
245 return convertCastInstruction(cast<TruncInst>(Inst),
246 Ice::InstCast::Trunc);
247 case Instruction::FPTrunc:
248 return convertCastInstruction(cast<FPTruncInst>(Inst),
249 Ice::InstCast::Fptrunc);
250 case Instruction::FPExt:
251 return convertCastInstruction(cast<FPExtInst>(Inst),
252 Ice::InstCast::Fpext);
253 case Instruction::FPToSI:
254 return convertCastInstruction(cast<FPToSIInst>(Inst),
255 Ice::InstCast::Fptosi);
256 case Instruction::FPToUI:
257 return convertCastInstruction(cast<FPToUIInst>(Inst),
258 Ice::InstCast::Fptoui);
259 case Instruction::SIToFP:
260 return convertCastInstruction(cast<SIToFPInst>(Inst),
261 Ice::InstCast::Sitofp);
262 case Instruction::UIToFP:
263 return convertCastInstruction(cast<UIToFPInst>(Inst),
264 Ice::InstCast::Uitofp);
265 case Instruction::BitCast:
266 return convertCastInstruction(cast<BitCastInst>(Inst),
267 Ice::InstCast::Bitcast);
268 case Instruction::Add:
269 return convertArithInstruction(Inst, Ice::InstArithmetic::Add);
270 case Instruction::Sub:
271 return convertArithInstruction(Inst, Ice::InstArithmetic::Sub);
272 case Instruction::Mul:
273 return convertArithInstruction(Inst, Ice::InstArithmetic::Mul);
274 case Instruction::UDiv:
275 return convertArithInstruction(Inst, Ice::InstArithmetic::Udiv);
276 case Instruction::SDiv:
277 return convertArithInstruction(Inst, Ice::InstArithmetic::Sdiv);
278 case Instruction::URem:
279 return convertArithInstruction(Inst, Ice::InstArithmetic::Urem);
280 case Instruction::SRem:
281 return convertArithInstruction(Inst, Ice::InstArithmetic::Srem);
282 case Instruction::Shl:
283 return convertArithInstruction(Inst, Ice::InstArithmetic::Shl);
284 case Instruction::LShr:
285 return convertArithInstruction(Inst, Ice::InstArithmetic::Lshr);
286 case Instruction::AShr:
287 return convertArithInstruction(Inst, Ice::InstArithmetic::Ashr);
288 case Instruction::FAdd:
289 return convertArithInstruction(Inst, Ice::InstArithmetic::Fadd);
290 case Instruction::FSub:
291 return convertArithInstruction(Inst, Ice::InstArithmetic::Fsub);
292 case Instruction::FMul:
293 return convertArithInstruction(Inst, Ice::InstArithmetic::Fmul);
294 case Instruction::FDiv:
295 return convertArithInstruction(Inst, Ice::InstArithmetic::Fdiv);
296 case Instruction::FRem:
297 return convertArithInstruction(Inst, Ice::InstArithmetic::Frem);
298 case Instruction::And:
299 return convertArithInstruction(Inst, Ice::InstArithmetic::And);
300 case Instruction::Or:
301 return convertArithInstruction(Inst, Ice::InstArithmetic::Or);
302 case Instruction::Xor:
303 return convertArithInstruction(Inst, Ice::InstArithmetic::Xor);
304 case Instruction::Call:
305 return convertCallInstruction(cast<CallInst>(Inst));
306 case Instruction::Alloca:
307 return convertAllocaInstruction(cast<AllocaInst>(Inst));
308 case Instruction::Unreachable:
309 return convertUnreachableInstruction(cast<UnreachableInst>(Inst));
310 default:
311 report_fatal_error(std::string("Invalid PNaCl instruction: ") +
312 LLVMObjectAsString(Inst));
313 }
314
315 llvm_unreachable("convertInstruction");
316 return NULL;
317 }
318
319 Ice::Inst *convertLoadInstruction(const LoadInst *Inst) {
320 Ice::Operand *Src = convertOperand(Inst, 0);
321 Ice::Variable *Dest = mapValueToIceVar(Inst);
322 return Ice::InstLoad::create(Func, Dest, Src);
323 }
324
325 Ice::Inst *convertStoreInstruction(const StoreInst *Inst) {
326 Ice::Operand *Addr = convertOperand(Inst, 1);
327 Ice::Operand *Val = convertOperand(Inst, 0);
328 return Ice::InstStore::create(Func, Val, Addr);
329 }
330
331 Ice::Inst *convertArithInstruction(const Instruction *Inst,
332 Ice::InstArithmetic::OpKind Opcode) {
333 const BinaryOperator *BinOp = cast<BinaryOperator>(Inst);
334 Ice::Operand *Src0 = convertOperand(Inst, 0);
335 Ice::Operand *Src1 = convertOperand(Inst, 1);
336 Ice::Variable *Dest = mapValueToIceVar(BinOp);
337 return Ice::InstArithmetic::create(Func, Opcode, Dest, Src0, Src1);
338 }
339
340 Ice::Inst *convertPHINodeInstruction(const PHINode *Inst) {
341 unsigned NumValues = Inst->getNumIncomingValues();
342 Ice::InstPhi *IcePhi =
343 Ice::InstPhi::create(Func, NumValues, mapValueToIceVar(Inst));
344 for (unsigned N = 0, E = NumValues; N != E; ++N) {
345 IcePhi->addArgument(convertOperand(Inst, N),
346 mapBasicBlockToNode(Inst->getIncomingBlock(N)));
347 }
348 return IcePhi;
349 }
350
351 Ice::Inst *convertBrInstruction(const BranchInst *Inst) {
352 if (Inst->isConditional()) {
353 Ice::Operand *Src = convertOperand(Inst, 0);
354 BasicBlock *BBThen = Inst->getSuccessor(0);
355 BasicBlock *BBElse = Inst->getSuccessor(1);
356 Ice::CfgNode *NodeThen = mapBasicBlockToNode(BBThen);
357 Ice::CfgNode *NodeElse = mapBasicBlockToNode(BBElse);
358 return Ice::InstBr::create(Func, Src, NodeThen, NodeElse);
359 } else {
360 BasicBlock *BBSucc = Inst->getSuccessor(0);
361 return Ice::InstBr::create(Func, mapBasicBlockToNode(BBSucc));
362 }
363 }
364
365 Ice::Inst *convertIntToPtrInstruction(const IntToPtrInst *Inst) {
366 Ice::Operand *Src = convertOperand(Inst, 0);
367 Ice::Variable *Dest = mapValueToIceVar(Inst, SubzeroPointerType);
368 return Ice::InstAssign::create(Func, Dest, Src);
369 }
370
371 Ice::Inst *convertPtrToIntInstruction(const PtrToIntInst *Inst) {
372 Ice::Operand *Src = convertOperand(Inst, 0);
373 Ice::Variable *Dest = mapValueToIceVar(Inst);
374 return Ice::InstAssign::create(Func, Dest, Src);
375 }
376
377 Ice::Inst *convertRetInstruction(const ReturnInst *Inst) {
378 Ice::Operand *RetOperand = convertOperand(Inst, 0);
379 if (RetOperand) {
380 return Ice::InstRet::create(Func, RetOperand);
381 } else {
382 return Ice::InstRet::create(Func);
383 }
384 }
385
386 Ice::Inst *convertCastInstruction(const Instruction *Inst,
387 Ice::InstCast::OpKind CastKind) {
388 Ice::Operand *Src = convertOperand(Inst, 0);
389 Ice::Variable *Dest = mapValueToIceVar(Inst);
390 return Ice::InstCast::create(Func, CastKind, Dest, Src);
391 }
392
393 Ice::Inst *convertICmpInstruction(const ICmpInst *Inst) {
394 Ice::Operand *Src0 = convertOperand(Inst, 0);
395 Ice::Operand *Src1 = convertOperand(Inst, 1);
396 Ice::Variable *Dest = mapValueToIceVar(Inst);
397
398 Ice::InstIcmp::ICond Cond;
399 switch (Inst->getPredicate()) {
400 default:
401 llvm_unreachable("ICmpInst predicate");
402 case CmpInst::ICMP_EQ:
403 Cond = Ice::InstIcmp::Eq;
404 break;
405 case CmpInst::ICMP_NE:
406 Cond = Ice::InstIcmp::Ne;
407 break;
408 case CmpInst::ICMP_UGT:
409 Cond = Ice::InstIcmp::Ugt;
410 break;
411 case CmpInst::ICMP_UGE:
412 Cond = Ice::InstIcmp::Uge;
413 break;
414 case CmpInst::ICMP_ULT:
415 Cond = Ice::InstIcmp::Ult;
416 break;
417 case CmpInst::ICMP_ULE:
418 Cond = Ice::InstIcmp::Ule;
419 break;
420 case CmpInst::ICMP_SGT:
421 Cond = Ice::InstIcmp::Sgt;
422 break;
423 case CmpInst::ICMP_SGE:
424 Cond = Ice::InstIcmp::Sge;
425 break;
426 case CmpInst::ICMP_SLT:
427 Cond = Ice::InstIcmp::Slt;
428 break;
429 case CmpInst::ICMP_SLE:
430 Cond = Ice::InstIcmp::Sle;
431 break;
432 }
433
434 return Ice::InstIcmp::create(Func, Cond, Dest, Src0, Src1);
435 }
436
437 Ice::Inst *convertFCmpInstruction(const FCmpInst *Inst) {
438 Ice::Operand *Src0 = convertOperand(Inst, 0);
439 Ice::Operand *Src1 = convertOperand(Inst, 1);
440 Ice::Variable *Dest = mapValueToIceVar(Inst);
441
442 Ice::InstFcmp::FCond Cond;
443 switch (Inst->getPredicate()) {
444
445 default:
446 llvm_unreachable("FCmpInst predicate");
447
448 case CmpInst::FCMP_FALSE:
449 Cond = Ice::InstFcmp::False;
450 break;
451 case CmpInst::FCMP_OEQ:
452 Cond = Ice::InstFcmp::Oeq;
453 break;
454 case CmpInst::FCMP_OGT:
455 Cond = Ice::InstFcmp::Ogt;
456 break;
457 case CmpInst::FCMP_OGE:
458 Cond = Ice::InstFcmp::Oge;
459 break;
460 case CmpInst::FCMP_OLT:
461 Cond = Ice::InstFcmp::Olt;
462 break;
463 case CmpInst::FCMP_OLE:
464 Cond = Ice::InstFcmp::Ole;
465 break;
466 case CmpInst::FCMP_ONE:
467 Cond = Ice::InstFcmp::One;
468 break;
469 case CmpInst::FCMP_ORD:
470 Cond = Ice::InstFcmp::Ord;
471 break;
472 case CmpInst::FCMP_UEQ:
473 Cond = Ice::InstFcmp::Ueq;
474 break;
475 case CmpInst::FCMP_UGT:
476 Cond = Ice::InstFcmp::Ugt;
477 break;
478 case CmpInst::FCMP_UGE:
479 Cond = Ice::InstFcmp::Uge;
480 break;
481 case CmpInst::FCMP_ULT:
482 Cond = Ice::InstFcmp::Ult;
483 break;
484 case CmpInst::FCMP_ULE:
485 Cond = Ice::InstFcmp::Ule;
486 break;
487 case CmpInst::FCMP_UNE:
488 Cond = Ice::InstFcmp::Une;
489 break;
490 case CmpInst::FCMP_UNO:
491 Cond = Ice::InstFcmp::Uno;
492 break;
493 case CmpInst::FCMP_TRUE:
494 Cond = Ice::InstFcmp::True;
495 break;
496 }
497
498 return Ice::InstFcmp::create(Func, Cond, Dest, Src0, Src1);
499 }
500
501 Ice::Inst *convertSelectInstruction(const SelectInst *Inst) {
502 Ice::Variable *Dest = mapValueToIceVar(Inst);
503 Ice::Operand *Cond = convertValue(Inst->getCondition());
504 Ice::Operand *Source1 = convertValue(Inst->getTrueValue());
505 Ice::Operand *Source2 = convertValue(Inst->getFalseValue());
506 return Ice::InstSelect::create(Func, Dest, Cond, Source1, Source2);
507 }
508
509 Ice::Inst *convertSwitchInstruction(const SwitchInst *Inst) {
510 Ice::Operand *Source = convertValue(Inst->getCondition());
511 Ice::CfgNode *LabelDefault = mapBasicBlockToNode(Inst->getDefaultDest());
512 unsigned NumCases = Inst->getNumCases();
513 Ice::InstSwitch *Switch =
514 Ice::InstSwitch::create(Func, NumCases, Source, LabelDefault);
515 unsigned CurrentCase = 0;
516 for (SwitchInst::ConstCaseIt I = Inst->case_begin(), E = Inst->case_end();
517 I != E; ++I, ++CurrentCase) {
518 uint64_t CaseValue = I.getCaseValue()->getZExtValue();
519 Ice::CfgNode *CaseSuccessor = mapBasicBlockToNode(I.getCaseSuccessor());
520 Switch->addBranch(CurrentCase, CaseValue, CaseSuccessor);
521 }
522 return Switch;
523 }
524
525 Ice::Inst *convertCallInstruction(const CallInst *Inst) {
526 Ice::Variable *Dest = mapValueToIceVar(Inst);
527 Ice::Operand *CallTarget = convertValue(Inst->getCalledValue());
528 unsigned NumArgs = Inst->getNumArgOperands();
529 // Note: Subzero doesn't (yet) do anything special with the Tail
530 // flag in the bitcode, i.e. CallInst::isTailCall().
531 Ice::InstCall *NewInst = NULL;
532 const Ice::Intrinsics::FullIntrinsicInfo *Info = NULL;
533
534 if (Ice::ConstantRelocatable *Target =
535 llvm::dyn_cast<Ice::ConstantRelocatable>(CallTarget)) {
536 // Check if this direct call is to an Intrinsic (starts with "llvm.")
537 static const char LLVMPrefix[] = "llvm.";
538 const size_t LLVMPrefixLen = strlen(LLVMPrefix);
539 Ice::IceString Name = Target->getName();
540 if (Name.substr(0, LLVMPrefixLen) == LLVMPrefix) {
541 Ice::IceString NameSuffix = Name.substr(LLVMPrefixLen);
542 Info = Ctx->getIntrinsicsInfo().find(NameSuffix);
543 if (!Info) {
544 report_fatal_error(std::string("Invalid PNaCl intrinsic call: ") +
545 LLVMObjectAsString(Inst));
546 }
547 NewInst = Ice::InstIntrinsicCall::create(Func, NumArgs, Dest,
548 CallTarget, Info->Info);
549 }
550 }
551
552 // Not an intrinsic call.
553 if (NewInst == NULL) {
554 NewInst = Ice::InstCall::create(Func, NumArgs, Dest, CallTarget);
555 }
556 for (unsigned i = 0; i < NumArgs; ++i) {
557 NewInst->addArg(convertOperand(Inst, i));
558 }
559 if (Info) {
560 validateIntrinsicCall(NewInst, Info);
561 }
562 return NewInst;
563 }
564
565 Ice::Inst *convertAllocaInstruction(const AllocaInst *Inst) {
566 // PNaCl bitcode only contains allocas of byte-granular objects.
567 Ice::Operand *ByteCount = convertValue(Inst->getArraySize());
568 uint32_t Align = Inst->getAlignment();
569 Ice::Variable *Dest = mapValueToIceVar(Inst, SubzeroPointerType);
570
571 return Ice::InstAlloca::create(Func, ByteCount, Align, Dest);
572 }
573
574 Ice::Inst *convertUnreachableInstruction(const UnreachableInst * /*Inst*/) {
575 return Ice::InstUnreachable::create(Func);
576 }
577
578 Ice::CfgNode *convertBasicBlock(const BasicBlock *BB) {
579 Ice::CfgNode *Node = mapBasicBlockToNode(BB);
580 for (BasicBlock::const_iterator II = BB->begin(), II_e = BB->end();
581 II != II_e; ++II) {
582 Ice::Inst *Inst = convertInstruction(II);
583 Node->appendInst(Inst);
584 }
585 return Node;
586 }
587
588 void validateIntrinsicCall(const Ice::InstCall *Call,
589 const Ice::Intrinsics::FullIntrinsicInfo *I) {
590 assert(I->NumTypes >= 1);
591 if (I->Signature[0] == Ice::IceType_void) {
592 if (Call->getDest() != NULL) {
593 report_fatal_error(
594 "Return value for intrinsic func w/ void return type.");
595 }
596 } else {
597 if (I->Signature[0] != Call->getDest()->getType()) {
598 report_fatal_error("Mismatched return types.");
599 }
600 }
601 if (Call->getNumArgs() + 1 != I->NumTypes) {
602 report_fatal_error("Mismatched # of args.");
603 }
604 for (size_t i = 1; i < I->NumTypes; ++i) {
605 if (Call->getArg(i - 1)->getType() != I->Signature[i]) {
606 report_fatal_error("Mismatched argument type.");
607 }
608 }
609 }
610
611 private:
612 // Data
613 Ice::GlobalContext *Ctx;
614 Ice::Cfg *Func;
615 Ice::CfgNode *CurrentNode;
616 Ice::Type SubzeroPointerType;
617 std::map<const Value *, Ice::Variable *> VarMap;
618 std::map<const BasicBlock *, Ice::CfgNode *> NodeMap;
619 };
620
621 static cl::list<Ice::VerboseItem> VerboseList( 31 static cl::list<Ice::VerboseItem> VerboseList(
622 "verbose", cl::CommaSeparated, 32 "verbose", cl::CommaSeparated,
623 cl::desc("Verbose options (can be comma-separated):"), 33 cl::desc("Verbose options (can be comma-separated):"),
624 cl::values( 34 cl::values(
625 clEnumValN(Ice::IceV_Instructions, "inst", "Print basic instructions"), 35 clEnumValN(Ice::IceV_Instructions, "inst", "Print basic instructions"),
626 clEnumValN(Ice::IceV_Deleted, "del", "Include deleted instructions"), 36 clEnumValN(Ice::IceV_Deleted, "del", "Include deleted instructions"),
627 clEnumValN(Ice::IceV_InstNumbers, "instnum", 37 clEnumValN(Ice::IceV_InstNumbers, "instnum",
628 "Print instruction numbers"), 38 "Print instruction numbers"),
629 clEnumValN(Ice::IceV_Preds, "pred", "Show predecessors"), 39 clEnumValN(Ice::IceV_Preds, "pred", "Show predecessors"),
630 clEnumValN(Ice::IceV_Succs, "succ", "Show successors"), 40 clEnumValN(Ice::IceV_Succs, "succ", "Show successors"),
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after
677 static cl::opt<bool> SubzeroTimingEnabled( 87 static cl::opt<bool> SubzeroTimingEnabled(
678 "timing", cl::desc("Enable breakdown timing of Subzero translation")); 88 "timing", cl::desc("Enable breakdown timing of Subzero translation"));
679 89
680 static cl::opt<NaClFileFormat> InputFileFormat( 90 static cl::opt<NaClFileFormat> InputFileFormat(
681 "bitcode-format", cl::desc("Define format of input file:"), 91 "bitcode-format", cl::desc("Define format of input file:"),
682 cl::values(clEnumValN(LLVMFormat, "llvm", "LLVM file (default)"), 92 cl::values(clEnumValN(LLVMFormat, "llvm", "LLVM file (default)"),
683 clEnumValN(PNaClFormat, "pnacl", "PNaCl bitcode file"), 93 clEnumValN(PNaClFormat, "pnacl", "PNaCl bitcode file"),
684 clEnumValEnd), 94 clEnumValEnd),
685 cl::init(LLVMFormat)); 95 cl::init(LLVMFormat));
686 96
97 static cl::opt<bool> BuildOnRead(
98 "build-on-read", cl::desc("Build ICE instructions when reading bitcode"),
99 cl::init(false));
100
687 int main(int argc, char **argv) { 101 int main(int argc, char **argv) {
688 int ExitStatus = 0;
689 102
690 cl::ParseCommandLineOptions(argc, argv); 103 cl::ParseCommandLineOptions(argc, argv);
691 104
692 // Parse the input LLVM IR file into a module.
693 SMDiagnostic Err;
694 Module *Mod;
695
696 {
697 Ice::Timer T;
698 Mod = NaClParseIRFile(IRFilename, InputFileFormat, Err, getGlobalContext());
699
700 if (SubzeroTimingEnabled) {
701 std::cerr << "[Subzero timing] IR Parsing: " << T.getElapsedSec()
702 << " sec\n";
703 }
704 }
705
706 if (!Mod) {
707 Err.print(argv[0], errs());
708 return 1;
709 }
710
711 Ice::VerboseMask VMask = Ice::IceV_None; 105 Ice::VerboseMask VMask = Ice::IceV_None;
712 for (unsigned i = 0; i != VerboseList.size(); ++i) 106 for (unsigned i = 0; i != VerboseList.size(); ++i)
713 VMask |= VerboseList[i]; 107 VMask |= VerboseList[i];
714 108
715 std::ofstream Ofs; 109 std::ofstream Ofs;
716 if (OutputFilename != "-") { 110 if (OutputFilename != "-") {
717 Ofs.open(OutputFilename.c_str(), std::ofstream::out); 111 Ofs.open(OutputFilename.c_str(), std::ofstream::out);
718 } 112 }
719 raw_os_ostream *Os = 113 raw_os_ostream *Os =
720 new raw_os_ostream(OutputFilename == "-" ? std::cout : Ofs); 114 new raw_os_ostream(OutputFilename == "-" ? std::cout : Ofs);
721 Os->SetUnbuffered(); 115 Os->SetUnbuffered();
722 std::ofstream Lfs; 116 std::ofstream Lfs;
723 if (LogFilename != "-") { 117 if (LogFilename != "-") {
724 Lfs.open(LogFilename.c_str(), std::ofstream::out); 118 Lfs.open(LogFilename.c_str(), std::ofstream::out);
725 } 119 }
726 raw_os_ostream *Ls = new raw_os_ostream(LogFilename == "-" ? std::cout : Lfs); 120 raw_os_ostream *Ls = new raw_os_ostream(LogFilename == "-" ? std::cout : Lfs);
727 Ls->SetUnbuffered(); 121 Ls->SetUnbuffered();
728 122
729 // Ideally, Func would be declared inside the loop and its object
730 // would be automatically deleted at the end of the loop iteration.
731 // However, emitting the constant pool requires a valid Cfg object,
732 // so we need to defer deleting the last non-empty Cfg object until
733 // outside the loop and after emitting the constant pool. TODO:
734 // Since all constants are globally pooled in the Ice::GlobalContext
735 // object, change all Ice::Constant related functions to use
736 // GlobalContext instead of Cfg, and then clean up this loop.
737 OwningPtr<Ice::Cfg> Func;
738 Ice::GlobalContext Ctx(Ls, Os, VMask, TargetArch, OptLevel, TestPrefix); 123 Ice::GlobalContext Ctx(Ls, Os, VMask, TargetArch, OptLevel, TestPrefix);
739 124
740 for (Module::const_iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) { 125 if (BuildOnRead) {
741 if (I->empty()) 126 std::cerr << "Direct build from bitcode not implemented yet!\n";
742 continue; 127 return 1;
743 LLVM2ICEConverter FunctionConverter(&Ctx); 128 } else {
744 129 // Parse the input LLVM IR file into a module.
745 Ice::Timer TConvert; 130 SMDiagnostic Err;
746 Func.reset(FunctionConverter.convertFunction(I)); 131 Ice::Timer T;
747 if (DisableInternal) 132 Module *Mod = NaClParseIRFile(IRFilename, InputFileFormat, Err,
748 Func->setInternal(false); 133 getGlobalContext());
749 134
750 if (SubzeroTimingEnabled) { 135 if (SubzeroTimingEnabled) {
751 std::cerr << "[Subzero timing] Convert function " 136 std::cerr << "[Subzero timing] IR Parsing: " << T.getElapsedSec()
752 << Func->getFunctionName() << ": " << TConvert.getElapsedSec()
753 << " sec\n"; 137 << " sec\n";
754 } 138 }
755 139
756 if (DisableTranslation) { 140 if (!Mod) {
757 Func->dump(); 141 Err.print(argv[0], errs());
758 } else { 142 return 1;
759 Ice::Timer TTranslate; 143 }
760 Func->translate();
761 if (SubzeroTimingEnabled) {
762 std::cerr << "[Subzero timing] Translate function "
763 << Func->getFunctionName() << ": "
764 << TTranslate.getElapsedSec() << " sec\n";
765 }
766 if (Func->hasError()) {
767 errs() << "ICE translation error: " << Func->getError() << "\n";
768 ExitStatus = 1;
769 }
770 144
771 Ice::Timer TEmit; 145 Ice::Converter Converter(&Ctx, DisableInternal, SubzeroTimingEnabled,
772 Func->emit(); 146 DisableTranslation);
773 if (SubzeroTimingEnabled) { 147 return Converter.convertToIce(Mod);
774 std::cerr << "[Subzero timing] Emit function "
775 << Func->getFunctionName() << ": " << TEmit.getElapsedSec()
776 << " sec\n";
777 }
778 }
779 } 148 }
780
781 if (!DisableTranslation && Func)
782 Func->getTarget()->emitConstants();
783
784 return ExitStatus;
785 } 149 }
OLDNEW
« no previous file with comments | « src/IceIntrinsics.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698