OSDN Git Service

4cd7091adfb78f93311157ffdd36c3025dc1f04f
[android-x86/external-swiftshader.git] / src / IceConverter.cpp
1 //===- subzero/src/IceConverter.cpp - Converts LLVM to Ice  ---------------===//
2 //
3 //                        The Subzero Code Generator
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief Implements the LLVM to ICE converter.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #include "IceConverter.h"
16
17 #include "IceCfg.h"
18 #include "IceCfgNode.h"
19 #include "IceClFlags.h"
20 #include "IceDefs.h"
21 #include "IceGlobalContext.h"
22 #include "IceGlobalInits.h"
23 #include "IceInst.h"
24 #include "IceOperand.h"
25 #include "IceTargetLowering.h"
26 #include "IceTypes.h"
27 #include "IceTypeConverter.h"
28
29 #ifdef __clang__
30 #pragma clang diagnostic push
31 #pragma clang diagnostic ignored "-Wunused-parameter"
32 #endif // __clang__
33
34 #include "llvm/IR/Constant.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/Instruction.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/LLVMContext.h"
40 #include "llvm/IR/Module.h"
41
42 #ifdef __clang__
43 #pragma clang diagnostic pop
44 #endif // __clang__
45
46 // TODO(kschimpf): Remove two namespaces being visible at once.
47 using namespace llvm;
48
49 namespace {
50
51 // Debugging helper
52 template <typename T> static std::string LLVMObjectAsString(const T *O) {
53   std::string Dump;
54   raw_string_ostream Stream(Dump);
55   O->print(Stream);
56   return Stream.str();
57 }
58
59 // Base class for converting LLVM to ICE.
60 // TODO(stichnot): Redesign Converter, LLVM2ICEConverter,
61 // LLVM2ICEFunctionConverter, and LLVM2ICEGlobalsConverter with respect to
62 // Translator.  In particular, the unique_ptr ownership rules in
63 // LLVM2ICEFunctionConverter.
64 class LLVM2ICEConverter {
65   LLVM2ICEConverter() = delete;
66   LLVM2ICEConverter(const LLVM2ICEConverter &) = delete;
67   LLVM2ICEConverter &operator=(const LLVM2ICEConverter &) = delete;
68
69 public:
70   explicit LLVM2ICEConverter(Ice::Converter &Converter)
71       : Converter(Converter), Ctx(Converter.getContext()),
72         TypeConverter(Converter.getModule()->getContext()) {}
73
74   Ice::Converter &getConverter() const { return Converter; }
75
76 protected:
77   Ice::Converter &Converter;
78   Ice::GlobalContext *Ctx;
79   const Ice::TypeConverter TypeConverter;
80 };
81
82 // Converter from LLVM functions to ICE. The entry point is the convertFunction
83 // method.
84 //
85 // Note: this currently assumes that the given IR was verified to be valid
86 // PNaCl bitcode. Otherwise, the behavior is undefined.
87 class LLVM2ICEFunctionConverter : LLVM2ICEConverter {
88   LLVM2ICEFunctionConverter() = delete;
89   LLVM2ICEFunctionConverter(const LLVM2ICEFunctionConverter &) = delete;
90   LLVM2ICEFunctionConverter &
91   operator=(const LLVM2ICEFunctionConverter &) = delete;
92
93 public:
94   explicit LLVM2ICEFunctionConverter(Ice::Converter &Converter)
95       : LLVM2ICEConverter(Converter), Func(nullptr) {}
96
97   void convertFunction(const Function *F) {
98     Func = Ice::Cfg::create(Ctx, Converter.getNextSequenceNumber());
99     Ice::Cfg::setCurrentCfg(Func.get());
100
101     VarMap.clear();
102     NodeMap.clear();
103     Func->setFunctionName(F->getName());
104     Func->setReturnType(convertToIceType(F->getReturnType()));
105     Func->setInternal(F->hasInternalLinkage());
106     Ice::TimerMarker T(Ice::TimerStack::TT_llvmConvert, Func.get());
107
108     // The initial definition/use of each arg is the entry node.
109     for (auto ArgI = F->arg_begin(), ArgE = F->arg_end(); ArgI != ArgE;
110          ++ArgI) {
111       Func->addArg(mapValueToIceVar(ArgI));
112     }
113
114     // Make an initial pass through the block list just to resolve the blocks
115     // in the original linearized order. Otherwise the ICE linearized order
116     // will be affected by branch targets in terminator instructions.
117     for (const BasicBlock &BBI : *F)
118       mapBasicBlockToNode(&BBI);
119     for (const BasicBlock &BBI : *F)
120       convertBasicBlock(&BBI);
121     Func->setEntryNode(mapBasicBlockToNode(&F->getEntryBlock()));
122     Func->computeInOutEdges();
123
124     Ice::Cfg::setCurrentCfg(nullptr);
125     Converter.translateFcn(std::move(Func));
126   }
127
128   // convertConstant() does not use Func or require it to be a valid Ice::Cfg
129   // pointer. As such, it's suitable for e.g. constructing global initializers.
130   Ice::Constant *convertConstant(const Constant *Const) {
131     if (const auto GV = dyn_cast<GlobalValue>(Const)) {
132       Ice::GlobalDeclaration *Decl = getConverter().getGlobalDeclaration(GV);
133       bool IsUndefined = false;
134       if (const auto *Func = llvm::dyn_cast<Ice::FunctionDeclaration>(Decl))
135         IsUndefined = Func->isProto();
136       else if (const auto *Var = llvm::dyn_cast<Ice::VariableDeclaration>(Decl))
137         IsUndefined = !Var->hasInitializer();
138       else
139         report_fatal_error("Unhandled GlobalDeclaration type");
140       if (IsUndefined)
141         return Ctx->getConstantExternSym(Decl->getName());
142       else {
143         const Ice::RelocOffsetT Offset = 0;
144         return Ctx->getConstantSym(Offset, Decl->getName(),
145                                    Decl->getSuppressMangling());
146       }
147     } else if (const auto CI = dyn_cast<ConstantInt>(Const)) {
148       Ice::Type Ty = convertToIceType(CI->getType());
149       return Ctx->getConstantInt(Ty, CI->getSExtValue());
150     } else if (const auto CFP = dyn_cast<ConstantFP>(Const)) {
151       Ice::Type Type = convertToIceType(CFP->getType());
152       if (Type == Ice::IceType_f32)
153         return Ctx->getConstantFloat(CFP->getValueAPF().convertToFloat());
154       else if (Type == Ice::IceType_f64)
155         return Ctx->getConstantDouble(CFP->getValueAPF().convertToDouble());
156       llvm_unreachable("Unexpected floating point type");
157       return nullptr;
158     } else if (const auto CU = dyn_cast<UndefValue>(Const)) {
159       return Ctx->getConstantUndef(convertToIceType(CU->getType()));
160     } else {
161       llvm_unreachable("Unhandled constant type");
162       return nullptr;
163     }
164   }
165
166 private:
167   // LLVM values (instructions, etc.) are mapped directly to ICE variables.
168   // mapValueToIceVar has a version that forces an ICE type on the variable,
169   // and a version that just uses convertToIceType on V.
170   Ice::Variable *mapValueToIceVar(const Value *V, Ice::Type IceTy) {
171     if (IceTy == Ice::IceType_void)
172       return nullptr;
173     if (VarMap.find(V) == VarMap.end()) {
174       VarMap[V] = Func->makeVariable(IceTy);
175       if (Ice::BuildDefs::dump())
176         VarMap[V]->setName(Func.get(), V->getName());
177     }
178     return VarMap[V];
179   }
180
181   Ice::Variable *mapValueToIceVar(const Value *V) {
182     return mapValueToIceVar(V, convertToIceType(V->getType()));
183   }
184
185   Ice::CfgNode *mapBasicBlockToNode(const BasicBlock *BB) {
186     if (NodeMap.find(BB) == NodeMap.end()) {
187       NodeMap[BB] = Func->makeNode();
188       if (Ice::BuildDefs::dump())
189         NodeMap[BB]->setName(BB->getName());
190     }
191     return NodeMap[BB];
192   }
193
194   Ice::Type convertToIceType(Type *LLVMTy) const {
195     Ice::Type IceTy = TypeConverter.convertToIceType(LLVMTy);
196     if (IceTy == Ice::IceType_NUM)
197       report_fatal_error(std::string("Invalid PNaCl type ") +
198                          LLVMObjectAsString(LLVMTy));
199     return IceTy;
200   }
201
202   // Given an LLVM instruction and an operand number, produce the Ice::Operand
203   // this refers to. If there's no such operand, return nullptr.
204   Ice::Operand *convertOperand(const Instruction *Inst, unsigned OpNum) {
205     if (OpNum >= Inst->getNumOperands()) {
206       return nullptr;
207     }
208     const Value *Op = Inst->getOperand(OpNum);
209     return convertValue(Op);
210   }
211
212   Ice::Operand *convertValue(const Value *Op) {
213     if (const auto Const = dyn_cast<Constant>(Op)) {
214       return convertConstant(Const);
215     } else {
216       return mapValueToIceVar(Op);
217     }
218   }
219
220   // Note: this currently assumes a 1x1 mapping between LLVM IR and Ice
221   // instructions.
222   Ice::Inst *convertInstruction(const Instruction *Inst) {
223     switch (Inst->getOpcode()) {
224     case Instruction::PHI:
225       return convertPHINodeInstruction(cast<PHINode>(Inst));
226     case Instruction::Br:
227       return convertBrInstruction(cast<BranchInst>(Inst));
228     case Instruction::Ret:
229       return convertRetInstruction(cast<ReturnInst>(Inst));
230     case Instruction::IntToPtr:
231       return convertIntToPtrInstruction(cast<IntToPtrInst>(Inst));
232     case Instruction::PtrToInt:
233       return convertPtrToIntInstruction(cast<PtrToIntInst>(Inst));
234     case Instruction::ICmp:
235       return convertICmpInstruction(cast<ICmpInst>(Inst));
236     case Instruction::FCmp:
237       return convertFCmpInstruction(cast<FCmpInst>(Inst));
238     case Instruction::Select:
239       return convertSelectInstruction(cast<SelectInst>(Inst));
240     case Instruction::Switch:
241       return convertSwitchInstruction(cast<SwitchInst>(Inst));
242     case Instruction::Load:
243       return convertLoadInstruction(cast<LoadInst>(Inst));
244     case Instruction::Store:
245       return convertStoreInstruction(cast<StoreInst>(Inst));
246     case Instruction::ZExt:
247       return convertCastInstruction(cast<ZExtInst>(Inst), Ice::InstCast::Zext);
248     case Instruction::SExt:
249       return convertCastInstruction(cast<SExtInst>(Inst), Ice::InstCast::Sext);
250     case Instruction::Trunc:
251       return convertCastInstruction(cast<TruncInst>(Inst),
252                                     Ice::InstCast::Trunc);
253     case Instruction::FPTrunc:
254       return convertCastInstruction(cast<FPTruncInst>(Inst),
255                                     Ice::InstCast::Fptrunc);
256     case Instruction::FPExt:
257       return convertCastInstruction(cast<FPExtInst>(Inst),
258                                     Ice::InstCast::Fpext);
259     case Instruction::FPToSI:
260       return convertCastInstruction(cast<FPToSIInst>(Inst),
261                                     Ice::InstCast::Fptosi);
262     case Instruction::FPToUI:
263       return convertCastInstruction(cast<FPToUIInst>(Inst),
264                                     Ice::InstCast::Fptoui);
265     case Instruction::SIToFP:
266       return convertCastInstruction(cast<SIToFPInst>(Inst),
267                                     Ice::InstCast::Sitofp);
268     case Instruction::UIToFP:
269       return convertCastInstruction(cast<UIToFPInst>(Inst),
270                                     Ice::InstCast::Uitofp);
271     case Instruction::BitCast:
272       return convertCastInstruction(cast<BitCastInst>(Inst),
273                                     Ice::InstCast::Bitcast);
274     case Instruction::Add:
275       return convertArithInstruction(Inst, Ice::InstArithmetic::Add);
276     case Instruction::Sub:
277       return convertArithInstruction(Inst, Ice::InstArithmetic::Sub);
278     case Instruction::Mul:
279       return convertArithInstruction(Inst, Ice::InstArithmetic::Mul);
280     case Instruction::UDiv:
281       return convertArithInstruction(Inst, Ice::InstArithmetic::Udiv);
282     case Instruction::SDiv:
283       return convertArithInstruction(Inst, Ice::InstArithmetic::Sdiv);
284     case Instruction::URem:
285       return convertArithInstruction(Inst, Ice::InstArithmetic::Urem);
286     case Instruction::SRem:
287       return convertArithInstruction(Inst, Ice::InstArithmetic::Srem);
288     case Instruction::Shl:
289       return convertArithInstruction(Inst, Ice::InstArithmetic::Shl);
290     case Instruction::LShr:
291       return convertArithInstruction(Inst, Ice::InstArithmetic::Lshr);
292     case Instruction::AShr:
293       return convertArithInstruction(Inst, Ice::InstArithmetic::Ashr);
294     case Instruction::FAdd:
295       return convertArithInstruction(Inst, Ice::InstArithmetic::Fadd);
296     case Instruction::FSub:
297       return convertArithInstruction(Inst, Ice::InstArithmetic::Fsub);
298     case Instruction::FMul:
299       return convertArithInstruction(Inst, Ice::InstArithmetic::Fmul);
300     case Instruction::FDiv:
301       return convertArithInstruction(Inst, Ice::InstArithmetic::Fdiv);
302     case Instruction::FRem:
303       return convertArithInstruction(Inst, Ice::InstArithmetic::Frem);
304     case Instruction::And:
305       return convertArithInstruction(Inst, Ice::InstArithmetic::And);
306     case Instruction::Or:
307       return convertArithInstruction(Inst, Ice::InstArithmetic::Or);
308     case Instruction::Xor:
309       return convertArithInstruction(Inst, Ice::InstArithmetic::Xor);
310     case Instruction::ExtractElement:
311       return convertExtractElementInstruction(cast<ExtractElementInst>(Inst));
312     case Instruction::InsertElement:
313       return convertInsertElementInstruction(cast<InsertElementInst>(Inst));
314     case Instruction::Call:
315       return convertCallInstruction(cast<CallInst>(Inst));
316     case Instruction::Alloca:
317       return convertAllocaInstruction(cast<AllocaInst>(Inst));
318     case Instruction::Unreachable:
319       return convertUnreachableInstruction(cast<UnreachableInst>(Inst));
320     default:
321       report_fatal_error(std::string("Invalid PNaCl instruction: ") +
322                          LLVMObjectAsString(Inst));
323     }
324
325     llvm_unreachable("convertInstruction");
326     return nullptr;
327   }
328
329   Ice::Inst *convertLoadInstruction(const LoadInst *Inst) {
330     Ice::Operand *Src = convertOperand(Inst, 0);
331     Ice::Variable *Dest = mapValueToIceVar(Inst);
332     return Ice::InstLoad::create(Func.get(), Dest, Src);
333   }
334
335   Ice::Inst *convertStoreInstruction(const StoreInst *Inst) {
336     Ice::Operand *Addr = convertOperand(Inst, 1);
337     Ice::Operand *Val = convertOperand(Inst, 0);
338     return Ice::InstStore::create(Func.get(), Val, Addr);
339   }
340
341   Ice::Inst *convertArithInstruction(const Instruction *Inst,
342                                      Ice::InstArithmetic::OpKind Opcode) {
343     const auto BinOp = cast<BinaryOperator>(Inst);
344     Ice::Operand *Src0 = convertOperand(Inst, 0);
345     Ice::Operand *Src1 = convertOperand(Inst, 1);
346     Ice::Variable *Dest = mapValueToIceVar(BinOp);
347     return Ice::InstArithmetic::create(Func.get(), Opcode, Dest, Src0, Src1);
348   }
349
350   Ice::Inst *convertPHINodeInstruction(const PHINode *Inst) {
351     unsigned NumValues = Inst->getNumIncomingValues();
352     Ice::InstPhi *IcePhi =
353         Ice::InstPhi::create(Func.get(), NumValues, mapValueToIceVar(Inst));
354     for (unsigned N = 0, E = NumValues; N != E; ++N) {
355       IcePhi->addArgument(convertOperand(Inst, N),
356                           mapBasicBlockToNode(Inst->getIncomingBlock(N)));
357     }
358     return IcePhi;
359   }
360
361   Ice::Inst *convertBrInstruction(const BranchInst *Inst) {
362     if (Inst->isConditional()) {
363       Ice::Operand *Src = convertOperand(Inst, 0);
364       BasicBlock *BBThen = Inst->getSuccessor(0);
365       BasicBlock *BBElse = Inst->getSuccessor(1);
366       Ice::CfgNode *NodeThen = mapBasicBlockToNode(BBThen);
367       Ice::CfgNode *NodeElse = mapBasicBlockToNode(BBElse);
368       return Ice::InstBr::create(Func.get(), Src, NodeThen, NodeElse);
369     } else {
370       BasicBlock *BBSucc = Inst->getSuccessor(0);
371       return Ice::InstBr::create(Func.get(), mapBasicBlockToNode(BBSucc));
372     }
373   }
374
375   Ice::Inst *convertIntToPtrInstruction(const IntToPtrInst *Inst) {
376     Ice::Operand *Src = convertOperand(Inst, 0);
377     Ice::Variable *Dest = mapValueToIceVar(Inst, Ice::getPointerType());
378     return Ice::InstAssign::create(Func.get(), Dest, Src);
379   }
380
381   Ice::Inst *convertPtrToIntInstruction(const PtrToIntInst *Inst) {
382     Ice::Operand *Src = convertOperand(Inst, 0);
383     Ice::Variable *Dest = mapValueToIceVar(Inst);
384     return Ice::InstAssign::create(Func.get(), Dest, Src);
385   }
386
387   Ice::Inst *convertRetInstruction(const ReturnInst *Inst) {
388     Ice::Operand *RetOperand = convertOperand(Inst, 0);
389     if (RetOperand) {
390       return Ice::InstRet::create(Func.get(), RetOperand);
391     } else {
392       return Ice::InstRet::create(Func.get());
393     }
394   }
395
396   Ice::Inst *convertCastInstruction(const Instruction *Inst,
397                                     Ice::InstCast::OpKind CastKind) {
398     Ice::Operand *Src = convertOperand(Inst, 0);
399     Ice::Variable *Dest = mapValueToIceVar(Inst);
400     return Ice::InstCast::create(Func.get(), CastKind, Dest, Src);
401   }
402
403   Ice::Inst *convertICmpInstruction(const ICmpInst *Inst) {
404     Ice::Operand *Src0 = convertOperand(Inst, 0);
405     Ice::Operand *Src1 = convertOperand(Inst, 1);
406     Ice::Variable *Dest = mapValueToIceVar(Inst);
407
408     Ice::InstIcmp::ICond Cond;
409     switch (Inst->getPredicate()) {
410     default:
411       llvm_unreachable("ICmpInst predicate");
412     case CmpInst::ICMP_EQ:
413       Cond = Ice::InstIcmp::Eq;
414       break;
415     case CmpInst::ICMP_NE:
416       Cond = Ice::InstIcmp::Ne;
417       break;
418     case CmpInst::ICMP_UGT:
419       Cond = Ice::InstIcmp::Ugt;
420       break;
421     case CmpInst::ICMP_UGE:
422       Cond = Ice::InstIcmp::Uge;
423       break;
424     case CmpInst::ICMP_ULT:
425       Cond = Ice::InstIcmp::Ult;
426       break;
427     case CmpInst::ICMP_ULE:
428       Cond = Ice::InstIcmp::Ule;
429       break;
430     case CmpInst::ICMP_SGT:
431       Cond = Ice::InstIcmp::Sgt;
432       break;
433     case CmpInst::ICMP_SGE:
434       Cond = Ice::InstIcmp::Sge;
435       break;
436     case CmpInst::ICMP_SLT:
437       Cond = Ice::InstIcmp::Slt;
438       break;
439     case CmpInst::ICMP_SLE:
440       Cond = Ice::InstIcmp::Sle;
441       break;
442     }
443
444     return Ice::InstIcmp::create(Func.get(), Cond, Dest, Src0, Src1);
445   }
446
447   Ice::Inst *convertFCmpInstruction(const FCmpInst *Inst) {
448     Ice::Operand *Src0 = convertOperand(Inst, 0);
449     Ice::Operand *Src1 = convertOperand(Inst, 1);
450     Ice::Variable *Dest = mapValueToIceVar(Inst);
451
452     Ice::InstFcmp::FCond Cond;
453     switch (Inst->getPredicate()) {
454
455     default:
456       llvm_unreachable("FCmpInst predicate");
457
458     case CmpInst::FCMP_FALSE:
459       Cond = Ice::InstFcmp::False;
460       break;
461     case CmpInst::FCMP_OEQ:
462       Cond = Ice::InstFcmp::Oeq;
463       break;
464     case CmpInst::FCMP_OGT:
465       Cond = Ice::InstFcmp::Ogt;
466       break;
467     case CmpInst::FCMP_OGE:
468       Cond = Ice::InstFcmp::Oge;
469       break;
470     case CmpInst::FCMP_OLT:
471       Cond = Ice::InstFcmp::Olt;
472       break;
473     case CmpInst::FCMP_OLE:
474       Cond = Ice::InstFcmp::Ole;
475       break;
476     case CmpInst::FCMP_ONE:
477       Cond = Ice::InstFcmp::One;
478       break;
479     case CmpInst::FCMP_ORD:
480       Cond = Ice::InstFcmp::Ord;
481       break;
482     case CmpInst::FCMP_UEQ:
483       Cond = Ice::InstFcmp::Ueq;
484       break;
485     case CmpInst::FCMP_UGT:
486       Cond = Ice::InstFcmp::Ugt;
487       break;
488     case CmpInst::FCMP_UGE:
489       Cond = Ice::InstFcmp::Uge;
490       break;
491     case CmpInst::FCMP_ULT:
492       Cond = Ice::InstFcmp::Ult;
493       break;
494     case CmpInst::FCMP_ULE:
495       Cond = Ice::InstFcmp::Ule;
496       break;
497     case CmpInst::FCMP_UNE:
498       Cond = Ice::InstFcmp::Une;
499       break;
500     case CmpInst::FCMP_UNO:
501       Cond = Ice::InstFcmp::Uno;
502       break;
503     case CmpInst::FCMP_TRUE:
504       Cond = Ice::InstFcmp::True;
505       break;
506     }
507
508     return Ice::InstFcmp::create(Func.get(), Cond, Dest, Src0, Src1);
509   }
510
511   Ice::Inst *convertExtractElementInstruction(const ExtractElementInst *Inst) {
512     Ice::Variable *Dest = mapValueToIceVar(Inst);
513     Ice::Operand *Source1 = convertValue(Inst->getOperand(0));
514     Ice::Operand *Source2 = convertValue(Inst->getOperand(1));
515     return Ice::InstExtractElement::create(Func.get(), Dest, Source1, Source2);
516   }
517
518   Ice::Inst *convertInsertElementInstruction(const InsertElementInst *Inst) {
519     Ice::Variable *Dest = mapValueToIceVar(Inst);
520     Ice::Operand *Source1 = convertValue(Inst->getOperand(0));
521     Ice::Operand *Source2 = convertValue(Inst->getOperand(1));
522     Ice::Operand *Source3 = convertValue(Inst->getOperand(2));
523     return Ice::InstInsertElement::create(Func.get(), Dest, Source1, Source2,
524                                           Source3);
525   }
526
527   Ice::Inst *convertSelectInstruction(const SelectInst *Inst) {
528     Ice::Variable *Dest = mapValueToIceVar(Inst);
529     Ice::Operand *Cond = convertValue(Inst->getCondition());
530     Ice::Operand *Source1 = convertValue(Inst->getTrueValue());
531     Ice::Operand *Source2 = convertValue(Inst->getFalseValue());
532     return Ice::InstSelect::create(Func.get(), Dest, Cond, Source1, Source2);
533   }
534
535   Ice::Inst *convertSwitchInstruction(const SwitchInst *Inst) {
536     Ice::Operand *Source = convertValue(Inst->getCondition());
537     Ice::CfgNode *LabelDefault = mapBasicBlockToNode(Inst->getDefaultDest());
538     unsigned NumCases = Inst->getNumCases();
539     Ice::InstSwitch *Switch =
540         Ice::InstSwitch::create(Func.get(), NumCases, Source, LabelDefault);
541     unsigned CurrentCase = 0;
542     for (SwitchInst::ConstCaseIt I = Inst->case_begin(), E = Inst->case_end();
543          I != E; ++I, ++CurrentCase) {
544       uint64_t CaseValue = I.getCaseValue()->getSExtValue();
545       Ice::CfgNode *CaseSuccessor = mapBasicBlockToNode(I.getCaseSuccessor());
546       Switch->addBranch(CurrentCase, CaseValue, CaseSuccessor);
547     }
548     return Switch;
549   }
550
551   Ice::Inst *convertCallInstruction(const CallInst *Inst) {
552     Ice::Variable *Dest = mapValueToIceVar(Inst);
553     Ice::Operand *CallTarget = convertValue(Inst->getCalledValue());
554     unsigned NumArgs = Inst->getNumArgOperands();
555     // Note: Subzero doesn't (yet) do anything special with the Tail flag in
556     // the bitcode, i.e. CallInst::isTailCall().
557     Ice::InstCall *NewInst = nullptr;
558     const Ice::Intrinsics::FullIntrinsicInfo *Info = nullptr;
559
560     if (const auto Target = dyn_cast<Ice::ConstantRelocatable>(CallTarget)) {
561       // Check if this direct call is to an Intrinsic (starts with "llvm.")
562       bool BadIntrinsic;
563       Info = Ctx->getIntrinsicsInfo().find(Target->getName(), BadIntrinsic);
564       if (BadIntrinsic) {
565         report_fatal_error(std::string("Invalid PNaCl intrinsic call: ") +
566                            LLVMObjectAsString(Inst));
567       }
568       if (Info)
569         NewInst = Ice::InstIntrinsicCall::create(Func.get(), NumArgs, Dest,
570                                                  CallTarget, Info->Info);
571     }
572
573     // Not an intrinsic call.
574     if (NewInst == nullptr) {
575       NewInst = Ice::InstCall::create(Func.get(), NumArgs, Dest, CallTarget,
576                                       Inst->isTailCall());
577     }
578     for (unsigned i = 0; i < NumArgs; ++i) {
579       NewInst->addArg(convertOperand(Inst, i));
580     }
581     if (Info) {
582       validateIntrinsicCall(NewInst, Info);
583     }
584     return NewInst;
585   }
586
587   Ice::Inst *convertAllocaInstruction(const AllocaInst *Inst) {
588     // PNaCl bitcode only contains allocas of byte-granular objects.
589     Ice::Operand *ByteCount = convertValue(Inst->getArraySize());
590     uint32_t Align = Inst->getAlignment();
591     Ice::Variable *Dest = mapValueToIceVar(Inst, Ice::getPointerType());
592
593     return Ice::InstAlloca::create(Func.get(), Dest, ByteCount, Align);
594   }
595
596   Ice::Inst *convertUnreachableInstruction(const UnreachableInst * /*Inst*/) {
597     return Ice::InstUnreachable::create(Func.get());
598   }
599
600   Ice::CfgNode *convertBasicBlock(const BasicBlock *BB) {
601     Ice::CfgNode *Node = mapBasicBlockToNode(BB);
602     for (const Instruction &II : *BB) {
603       Ice::Inst *Inst = convertInstruction(&II);
604       Node->appendInst(Inst);
605     }
606     return Node;
607   }
608
609   void validateIntrinsicCall(const Ice::InstCall *Call,
610                              const Ice::Intrinsics::FullIntrinsicInfo *I) {
611     Ice::SizeT ArgIndex = 0;
612     switch (I->validateCall(Call, ArgIndex)) {
613     case Ice::Intrinsics::IsValidCall:
614       break;
615     case Ice::Intrinsics::BadReturnType: {
616       std::string Buffer;
617       raw_string_ostream StrBuf(Buffer);
618       StrBuf << "Intrinsic call expects return type " << I->getReturnType()
619              << ". Found: " << Call->getReturnType();
620       report_fatal_error(StrBuf.str());
621       break;
622     }
623     case Ice::Intrinsics::WrongNumOfArgs: {
624       std::string Buffer;
625       raw_string_ostream StrBuf(Buffer);
626       StrBuf << "Intrinsic call expects " << I->getNumArgs()
627              << ". Found: " << Call->getNumArgs();
628       report_fatal_error(StrBuf.str());
629       break;
630     }
631     case Ice::Intrinsics::WrongCallArgType: {
632       std::string Buffer;
633       raw_string_ostream StrBuf(Buffer);
634       StrBuf << "Intrinsic call argument " << ArgIndex << " expects type "
635              << I->getArgType(ArgIndex)
636              << ". Found: " << Call->getArg(ArgIndex)->getType();
637       report_fatal_error(StrBuf.str());
638       break;
639     }
640     }
641   }
642
643 private:
644   // Data
645   std::unique_ptr<Ice::Cfg> Func;
646   std::map<const Value *, Ice::Variable *> VarMap;
647   std::map<const BasicBlock *, Ice::CfgNode *> NodeMap;
648 };
649
650 // Converter from LLVM global variables to ICE. The entry point is the
651 // convertGlobalsToIce method.
652 //
653 // Note: this currently assumes that the given IR was verified to be valid
654 // PNaCl bitcode. Otherwise, the behavior is undefined.
655 class LLVM2ICEGlobalsConverter : public LLVM2ICEConverter {
656   LLVM2ICEGlobalsConverter() = delete;
657   LLVM2ICEGlobalsConverter(const LLVM2ICEGlobalsConverter &) = delete;
658   LLVM2ICEGlobalsConverter &
659   operator=(const LLVM2ICEGlobalsConverter &) = delete;
660
661 public:
662   explicit LLVM2ICEGlobalsConverter(Ice::Converter &Converter)
663       : LLVM2ICEConverter(Converter) {}
664
665   /// Converts global variables, and their initializers into ICE global variable
666   /// declarations, for module Mod. Returns the set of converted declarations.
667   std::unique_ptr<Ice::VariableDeclarationList>
668   convertGlobalsToIce(Module *Mod);
669
670 private:
671   // Adds the Initializer to the list of initializers for the Global variable
672   // declaration.
673   void addGlobalInitializer(Ice::VariableDeclaration &Global,
674                             const Constant *Initializer) {
675     constexpr bool HasOffset = false;
676     constexpr Ice::RelocOffsetT Offset = 0;
677     addGlobalInitializer(Global, Initializer, HasOffset, Offset);
678   }
679
680   // Adds Initializer to the list of initializers for Global variable
681   // declaration. HasOffset is true only if Initializer is a relocation
682   // initializer and Offset should be added to the relocation.
683   void addGlobalInitializer(Ice::VariableDeclaration &Global,
684                             const Constant *Initializer, bool HasOffset,
685                             Ice::RelocOffsetT Offset);
686
687   // Converts the given constant C to the corresponding integer literal it
688   // contains.
689   Ice::RelocOffsetT getIntegerLiteralConstant(const Value *C) {
690     const auto CI = dyn_cast<ConstantInt>(C);
691     if (CI && CI->getType()->isIntegerTy(32))
692       return CI->getSExtValue();
693
694     std::string Buffer;
695     raw_string_ostream StrBuf(Buffer);
696     StrBuf << "Constant not i32 literal: " << *C;
697     report_fatal_error(StrBuf.str());
698     return 0;
699   }
700 };
701
702 std::unique_ptr<Ice::VariableDeclarationList>
703 LLVM2ICEGlobalsConverter::convertGlobalsToIce(Module *Mod) {
704   std::unique_ptr<Ice::VariableDeclarationList> VariableDeclarations(
705       new Ice::VariableDeclarationList);
706   for (Module::const_global_iterator I = Mod->global_begin(),
707                                      E = Mod->global_end();
708        I != E; ++I) {
709
710     const GlobalVariable *GV = I;
711
712     Ice::GlobalDeclaration *Var = getConverter().getGlobalDeclaration(GV);
713     auto *VarDecl = cast<Ice::VariableDeclaration>(Var);
714     VariableDeclarations->push_back(VarDecl);
715
716     if (!GV->hasInternalLinkage() && GV->hasInitializer()) {
717       std::string Buffer;
718       raw_string_ostream StrBuf(Buffer);
719       StrBuf << "Can't define external global declaration: " << GV->getName();
720       report_fatal_error(StrBuf.str());
721     }
722
723     if (!GV->hasInitializer()) {
724       if (Ctx->getFlags().getAllowUninitializedGlobals())
725         continue;
726       else {
727         std::string Buffer;
728         raw_string_ostream StrBuf(Buffer);
729         StrBuf << "Global declaration missing initializer: " << GV->getName();
730         report_fatal_error(StrBuf.str());
731       }
732     }
733
734     const Constant *Initializer = GV->getInitializer();
735     if (const auto CompoundInit = dyn_cast<ConstantStruct>(Initializer)) {
736       for (ConstantStruct::const_op_iterator I = CompoundInit->op_begin(),
737                                              E = CompoundInit->op_end();
738            I != E; ++I) {
739         if (const auto Init = dyn_cast<Constant>(I)) {
740           addGlobalInitializer(*VarDecl, Init);
741         }
742       }
743     } else {
744       addGlobalInitializer(*VarDecl, Initializer);
745     }
746   }
747   return VariableDeclarations;
748 }
749
750 void LLVM2ICEGlobalsConverter::addGlobalInitializer(
751     Ice::VariableDeclaration &Global, const Constant *Initializer,
752     bool HasOffset, Ice::RelocOffsetT Offset) {
753   (void)HasOffset;
754   assert(HasOffset || Offset == 0);
755
756   if (const auto CDA = dyn_cast<ConstantDataArray>(Initializer)) {
757     assert(!HasOffset && isa<IntegerType>(CDA->getElementType()) &&
758            (cast<IntegerType>(CDA->getElementType())->getBitWidth() == 8));
759     Global.addInitializer(Ice::VariableDeclaration::DataInitializer::create(
760         CDA->getRawDataValues().data(), CDA->getNumElements()));
761     return;
762   }
763
764   if (isa<ConstantAggregateZero>(Initializer)) {
765     if (const auto AT = dyn_cast<ArrayType>(Initializer->getType())) {
766       assert(!HasOffset && isa<IntegerType>(AT->getElementType()) &&
767              (cast<IntegerType>(AT->getElementType())->getBitWidth() == 8));
768       Global.addInitializer(Ice::VariableDeclaration::ZeroInitializer::create(
769           AT->getNumElements()));
770     } else {
771       llvm_unreachable("Unhandled constant aggregate zero type");
772     }
773     return;
774   }
775
776   if (const auto Exp = dyn_cast<ConstantExpr>(Initializer)) {
777     switch (Exp->getOpcode()) {
778     case Instruction::Add:
779       assert(!HasOffset);
780       addGlobalInitializer(Global, Exp->getOperand(0), true,
781                            getIntegerLiteralConstant(Exp->getOperand(1)));
782       return;
783     case Instruction::PtrToInt: {
784       assert(TypeConverter.convertToIceType(Exp->getType()) ==
785              Ice::getPointerType());
786       const auto GV = dyn_cast<GlobalValue>(Exp->getOperand(0));
787       assert(GV);
788       const Ice::GlobalDeclaration *Addr =
789           getConverter().getGlobalDeclaration(GV);
790       Global.addInitializer(Ice::VariableDeclaration::RelocInitializer::create(
791           Addr, {Ice::RelocOffset::create(Ctx, Offset)}));
792       return;
793     }
794     default:
795       break;
796     }
797   }
798
799   std::string Buffer;
800   raw_string_ostream StrBuf(Buffer);
801   StrBuf << "Unhandled global initializer: " << Initializer;
802   report_fatal_error(StrBuf.str());
803 }
804
805 } // end of anonymous namespace
806
807 namespace Ice {
808
809 void Converter::nameUnnamedGlobalVariables(Module *Mod) {
810   const IceString &GlobalPrefix = Ctx->getFlags().getDefaultGlobalPrefix();
811   if (GlobalPrefix.empty())
812     return;
813   uint32_t NameIndex = 0;
814   for (auto V = Mod->global_begin(), E = Mod->global_end(); V != E; ++V) {
815     if (!V->hasName()) {
816       V->setName(createUnnamedName(GlobalPrefix, NameIndex));
817       ++NameIndex;
818     } else {
819       checkIfUnnamedNameSafe(V->getName(), "global", GlobalPrefix);
820     }
821   }
822 }
823
824 void Converter::nameUnnamedFunctions(Module *Mod) {
825   const IceString &FunctionPrefix = Ctx->getFlags().getDefaultFunctionPrefix();
826   if (FunctionPrefix.empty())
827     return;
828   uint32_t NameIndex = 0;
829   for (Function &F : *Mod) {
830     if (!F.hasName()) {
831       F.setName(createUnnamedName(FunctionPrefix, NameIndex));
832       ++NameIndex;
833     } else {
834       checkIfUnnamedNameSafe(F.getName(), "function", FunctionPrefix);
835     }
836   }
837 }
838
839 void Converter::convertToIce() {
840   TimerMarker T(TimerStack::TT_convertToIce, Ctx);
841   nameUnnamedGlobalVariables(Mod);
842   nameUnnamedFunctions(Mod);
843   installGlobalDeclarations(Mod);
844   convertGlobals(Mod);
845   convertFunctions();
846 }
847
848 GlobalDeclaration *Converter::getGlobalDeclaration(const GlobalValue *V) {
849   GlobalDeclarationMapType::const_iterator Pos = GlobalDeclarationMap.find(V);
850   if (Pos == GlobalDeclarationMap.end()) {
851     std::string Buffer;
852     raw_string_ostream StrBuf(Buffer);
853     StrBuf << "Can't find global declaration for: " << V->getName();
854     report_fatal_error(StrBuf.str());
855   }
856   return Pos->second;
857 }
858
859 void Converter::installGlobalDeclarations(Module *Mod) {
860   const TypeConverter Converter(Mod->getContext());
861   // Install function declarations.
862   for (const Function &Func : *Mod) {
863     FuncSigType Signature;
864     FunctionType *FuncType = Func.getFunctionType();
865     Signature.setReturnType(
866         Converter.convertToIceType(FuncType->getReturnType()));
867     for (size_t I = 0; I < FuncType->getNumParams(); ++I) {
868       Signature.appendArgType(
869           Converter.convertToIceType(FuncType->getParamType(I)));
870     }
871     auto *IceFunc = FunctionDeclaration::create(
872         Ctx, Signature, Func.getCallingConv(), Func.getLinkage(), Func.empty());
873     IceFunc->setName(Func.getName());
874     if (!IceFunc->verifyLinkageCorrect(Ctx)) {
875       std::string Buffer;
876       raw_string_ostream StrBuf(Buffer);
877       StrBuf << "Function " << IceFunc->getName()
878              << " has incorrect linkage: " << IceFunc->getLinkageName();
879       if (IceFunc->isExternal())
880         StrBuf << "\n  Use flag -allow-externally-defined-symbols to override";
881       report_fatal_error(StrBuf.str());
882     }
883     if (!IceFunc->validateTypeSignature(Ctx))
884       report_fatal_error(IceFunc->getTypeSignatureError(Ctx));
885     GlobalDeclarationMap[&Func] = IceFunc;
886   }
887   // Install global variable declarations.
888   for (Module::const_global_iterator I = Mod->global_begin(),
889                                      E = Mod->global_end();
890        I != E; ++I) {
891     const GlobalVariable *GV = I;
892     auto *Var = VariableDeclaration::create(Ctx);
893     Var->setName(GV->getName());
894     Var->setAlignment(GV->getAlignment());
895     Var->setIsConstant(GV->isConstant());
896     Var->setLinkage(GV->getLinkage());
897     if (!Var->verifyLinkageCorrect(Ctx)) {
898       std::string Buffer;
899       raw_string_ostream StrBuf(Buffer);
900       StrBuf << "Global " << Var->getName()
901              << " has incorrect linkage: " << Var->getLinkageName();
902       if (Var->isExternal())
903         StrBuf << "\n  Use flag -allow-externally-defined-symbols to override";
904       report_fatal_error(StrBuf.str());
905     }
906     GlobalDeclarationMap[GV] = Var;
907   }
908 }
909
910 void Converter::convertGlobals(Module *Mod) {
911   lowerGlobals(LLVM2ICEGlobalsConverter(*this).convertGlobalsToIce(Mod));
912 }
913
914 void Converter::convertFunctions() {
915   const TimerStackIdT StackID = GlobalContext::TSK_Funcs;
916   for (const Function &I : *Mod) {
917     if (I.empty())
918       continue;
919
920     TimerIdT TimerID = 0;
921     const bool TimeThisFunction = Ctx->getFlags().getTimeEachFunction();
922     if (TimeThisFunction) {
923       TimerID = Ctx->getTimerID(StackID, I.getName());
924       Ctx->pushTimer(TimerID, StackID);
925     }
926     LLVM2ICEFunctionConverter FunctionConverter(*this);
927     FunctionConverter.convertFunction(&I);
928     if (TimeThisFunction)
929       Ctx->popTimer(TimerID, StackID);
930   }
931 }
932
933 } // end of namespace Ice