blob: 69056ac8fea73b884ade6cd6db5e821ce347736d [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +000025#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskeyb2efb852006-01-04 22:28:25 +000026#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000032#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetLowering.h"
37#include "llvm/Target/TargetMachine.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7944d9d2005-01-12 03:41:21 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000041#include "llvm/Support/Debug.h"
42#include <map>
Chris Lattner4e4b5762006-02-01 18:59:47 +000043#include <set>
Chris Lattner1c08c712005-01-07 07:47:53 +000044#include <iostream>
Jeff Cohen7e881032006-02-24 02:52:40 +000045#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000046using namespace llvm;
47
Chris Lattnerda8abb02005-09-01 18:44:10 +000048#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000049static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000050ViewISelDAGs("view-isel-dags", cl::Hidden,
51 cl::desc("Pop up a window to show isel dags as they are selected"));
52static cl::opt<bool>
53ViewSchedDAGs("view-sched-dags", cl::Hidden,
54 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000055#else
Evan Chenga9c20912006-01-21 02:32:06 +000056static const bool ViewISelDAGs = 0;
57static const bool ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000058#endif
59
Chris Lattner20a49212006-03-10 07:49:12 +000060// Scheduling heuristics
61enum SchedHeuristics {
62 defaultScheduling, // Let the target specify its preference.
63 noScheduling, // No scheduling, emit breadth first sequence.
64 simpleScheduling, // Two pass, min. critical path, max. utilization.
65 simpleNoItinScheduling, // Same as above exact using generic latency.
66 listSchedulingBURR, // Bottom up reg reduction list scheduling.
67 listSchedulingTD // Top-down list scheduler.
68};
69
Evan Cheng4ef10862006-01-23 07:01:07 +000070namespace {
71 cl::opt<SchedHeuristics>
72 ISHeuristic(
73 "sched",
74 cl::desc("Choose scheduling style"),
Evan Cheng3f239522006-01-25 09:12:57 +000075 cl::init(defaultScheduling),
Evan Cheng4ef10862006-01-23 07:01:07 +000076 cl::values(
Evan Cheng3f239522006-01-25 09:12:57 +000077 clEnumValN(defaultScheduling, "default",
78 "Target preferred scheduling style"),
Evan Cheng4ef10862006-01-23 07:01:07 +000079 clEnumValN(noScheduling, "none",
Jim Laskey17d52f72006-01-23 13:34:04 +000080 "No scheduling: breadth first sequencing"),
Evan Cheng4ef10862006-01-23 07:01:07 +000081 clEnumValN(simpleScheduling, "simple",
82 "Simple two pass scheduling: minimize critical path "
83 "and maximize processor utilization"),
84 clEnumValN(simpleNoItinScheduling, "simple-noitin",
85 "Simple two pass scheduling: Same as simple "
86 "except using generic latency"),
Evan Cheng3f239522006-01-25 09:12:57 +000087 clEnumValN(listSchedulingBURR, "list-burr",
Evan Chengf0f9c902006-01-23 08:26:10 +000088 "Bottom up register reduction list scheduling"),
Chris Lattner03fc53c2006-03-06 00:22:00 +000089 clEnumValN(listSchedulingTD, "list-td",
90 "Top-down list scheduler"),
Evan Cheng4ef10862006-01-23 07:01:07 +000091 clEnumValEnd));
92} // namespace
93
Chris Lattner864635a2006-02-22 22:37:12 +000094namespace {
95 /// RegsForValue - This struct represents the physical registers that a
96 /// particular value is assigned and the type information about the value.
97 /// This is needed because values can be promoted into larger registers and
98 /// expanded into multiple smaller registers than the value.
99 struct RegsForValue {
100 /// Regs - This list hold the register (for legal and promoted values)
101 /// or register set (for expanded values) that the value should be assigned
102 /// to.
103 std::vector<unsigned> Regs;
104
105 /// RegVT - The value type of each register.
106 ///
107 MVT::ValueType RegVT;
108
109 /// ValueVT - The value type of the LLVM value, which may be promoted from
110 /// RegVT or made from merging the two expanded parts.
111 MVT::ValueType ValueVT;
112
113 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
114
115 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
116 : RegVT(regvt), ValueVT(valuevt) {
117 Regs.push_back(Reg);
118 }
119 RegsForValue(const std::vector<unsigned> &regs,
120 MVT::ValueType regvt, MVT::ValueType valuevt)
121 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
122 }
123
124 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
125 /// this value and returns the result as a ValueVT value. This uses
126 /// Chain/Flag as the input and updates them for the output Chain/Flag.
127 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000128 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000129
130 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
131 /// specified value into the registers specified by this object. This uses
132 /// Chain/Flag as the input and updates them for the output Chain/Flag.
133 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000134 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000135
136 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
137 /// operand list. This adds the code marker and includes the number of
138 /// values added into it.
139 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000140 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000141 };
142}
Evan Cheng4ef10862006-01-23 07:01:07 +0000143
Chris Lattner1c08c712005-01-07 07:47:53 +0000144namespace llvm {
145 //===--------------------------------------------------------------------===//
146 /// FunctionLoweringInfo - This contains information that is global to a
147 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000148 class FunctionLoweringInfo {
149 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000150 TargetLowering &TLI;
151 Function &Fn;
152 MachineFunction &MF;
153 SSARegMap *RegMap;
154
155 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
156
157 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
158 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
159
160 /// ValueMap - Since we emit code for the function a basic block at a time,
161 /// we must remember which virtual registers hold the values for
162 /// cross-basic-block values.
163 std::map<const Value*, unsigned> ValueMap;
164
165 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
166 /// the entry block. This allows the allocas to be efficiently referenced
167 /// anywhere in the function.
168 std::map<const AllocaInst*, int> StaticAllocaMap;
169
170 unsigned MakeReg(MVT::ValueType VT) {
171 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
172 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000173
Chris Lattner3c384492006-03-16 19:51:18 +0000174 unsigned CreateRegForValue(const Value *V);
175
Chris Lattner1c08c712005-01-07 07:47:53 +0000176 unsigned InitializeRegForValue(const Value *V) {
177 unsigned &R = ValueMap[V];
178 assert(R == 0 && "Already initialized this value register!");
179 return R = CreateRegForValue(V);
180 }
181 };
182}
183
184/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
185/// PHI nodes or outside of the basic block that defines it.
186static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
187 if (isa<PHINode>(I)) return true;
188 BasicBlock *BB = I->getParent();
189 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
190 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
191 return true;
192 return false;
193}
194
Chris Lattnerbf209482005-10-30 19:42:35 +0000195/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
196/// entry block, return true.
197static bool isOnlyUsedInEntryBlock(Argument *A) {
198 BasicBlock *Entry = A->getParent()->begin();
199 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
200 if (cast<Instruction>(*UI)->getParent() != Entry)
201 return false; // Use not in entry block.
202 return true;
203}
204
Chris Lattner1c08c712005-01-07 07:47:53 +0000205FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000206 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000207 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
208
Chris Lattnerbf209482005-10-30 19:42:35 +0000209 // Create a vreg for each argument register that is not dead and is used
210 // outside of the entry block for the function.
211 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
212 AI != E; ++AI)
213 if (!isOnlyUsedInEntryBlock(AI))
214 InitializeRegForValue(AI);
215
Chris Lattner1c08c712005-01-07 07:47:53 +0000216 // Initialize the mapping of values to registers. This is only set up for
217 // instruction values that are used outside of the block that defines
218 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000219 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000220 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
221 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
222 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
223 const Type *Ty = AI->getAllocatedType();
224 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000225 unsigned Align =
226 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
227 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000228
229 // If the alignment of the value is smaller than the size of the value,
230 // and if the size of the value is particularly small (<= 8 bytes),
231 // round up to the size of the value for potentially better performance.
232 //
233 // FIXME: This could be made better with a preferred alignment hook in
234 // TargetData. It serves primarily to 8-byte align doubles for X86.
235 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner2dfa8192005-10-18 22:11:42 +0000236 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000237 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000238 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000239 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000240 }
241
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000242 for (; BB != EB; ++BB)
243 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000244 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
245 if (!isa<AllocaInst>(I) ||
246 !StaticAllocaMap.count(cast<AllocaInst>(I)))
247 InitializeRegForValue(I);
248
249 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
250 // also creates the initial PHI MachineInstrs, though none of the input
251 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000252 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000253 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
254 MBBMap[BB] = MBB;
255 MF.getBasicBlockList().push_back(MBB);
256
257 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
258 // appropriate.
259 PHINode *PN;
260 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000261 (PN = dyn_cast<PHINode>(I)); ++I)
262 if (!PN->use_empty()) {
263 unsigned NumElements =
264 TLI.getNumElements(TLI.getValueType(PN->getType()));
265 unsigned PHIReg = ValueMap[PN];
266 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
267 for (unsigned i = 0; i != NumElements; ++i)
268 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
269 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000270 }
271}
272
Chris Lattner3c384492006-03-16 19:51:18 +0000273/// CreateRegForValue - Allocate the appropriate number of virtual registers of
274/// the correctly promoted or expanded types. Assign these registers
275/// consecutive vreg numbers and return the first assigned number.
276unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
277 MVT::ValueType VT = TLI.getValueType(V->getType());
278
279 // The number of multiples of registers that we need, to, e.g., split up
280 // a <2 x int64> -> 4 x i32 registers.
281 unsigned NumVectorRegs = 1;
282
283 // If this is a packed type, figure out what type it will decompose into
284 // and how many of the elements it will use.
285 if (VT == MVT::Vector) {
286 const PackedType *PTy = cast<PackedType>(V->getType());
287 unsigned NumElts = PTy->getNumElements();
288 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
289
290 // Divide the input until we get to a supported size. This will always
291 // end with a scalar if the target doesn't support vectors.
292 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
293 NumElts >>= 1;
294 NumVectorRegs <<= 1;
295 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000296 if (NumElts == 1)
297 VT = EltTy;
298 else
299 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000300 }
301
302 // The common case is that we will only create one register for this
303 // value. If we have that case, create and return the virtual register.
304 unsigned NV = TLI.getNumElements(VT);
305 if (NV == 1) {
306 // If we are promoting this value, pick the next largest supported type.
307 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
308 unsigned Reg = MakeReg(PromotedType);
309 // If this is a vector of supported or promoted types (e.g. 4 x i16),
310 // create all of the registers.
311 for (unsigned i = 1; i != NumVectorRegs; ++i)
312 MakeReg(PromotedType);
313 return Reg;
314 }
315
316 // If this value is represented with multiple target registers, make sure
317 // to create enough consecutive registers of the right (smaller) type.
318 unsigned NT = VT-1; // Find the type to use.
319 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
320 --NT;
321
322 unsigned R = MakeReg((MVT::ValueType)NT);
323 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
324 MakeReg((MVT::ValueType)NT);
325 return R;
326}
Chris Lattner1c08c712005-01-07 07:47:53 +0000327
328//===----------------------------------------------------------------------===//
329/// SelectionDAGLowering - This is the common target-independent lowering
330/// implementation that is parameterized by a TargetLowering object.
331/// Also, targets can overload any lowering method.
332///
333namespace llvm {
334class SelectionDAGLowering {
335 MachineBasicBlock *CurMBB;
336
337 std::map<const Value*, SDOperand> NodeMap;
338
Chris Lattnerd3948112005-01-17 22:19:26 +0000339 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
340 /// them up and then emit token factor nodes when possible. This allows us to
341 /// get simple disambiguation between loads without worrying about alias
342 /// analysis.
343 std::vector<SDOperand> PendingLoads;
344
Chris Lattner1c08c712005-01-07 07:47:53 +0000345public:
346 // TLI - This is information that describes the available target features we
347 // need for lowering. This indicates when operations are unavailable,
348 // implemented with a libcall, etc.
349 TargetLowering &TLI;
350 SelectionDAG &DAG;
351 const TargetData &TD;
352
353 /// FuncInfo - Information about the function as a whole.
354 ///
355 FunctionLoweringInfo &FuncInfo;
356
357 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000358 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000359 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
360 FuncInfo(funcinfo) {
361 }
362
Chris Lattnera651cf62005-01-17 19:43:36 +0000363 /// getRoot - Return the current virtual root of the Selection DAG.
364 ///
365 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000366 if (PendingLoads.empty())
367 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000368
Chris Lattnerd3948112005-01-17 22:19:26 +0000369 if (PendingLoads.size() == 1) {
370 SDOperand Root = PendingLoads[0];
371 DAG.setRoot(Root);
372 PendingLoads.clear();
373 return Root;
374 }
375
376 // Otherwise, we have to make a token factor node.
377 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
378 PendingLoads.clear();
379 DAG.setRoot(Root);
380 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000381 }
382
Chris Lattner1c08c712005-01-07 07:47:53 +0000383 void visit(Instruction &I) { visit(I.getOpcode(), I); }
384
385 void visit(unsigned Opcode, User &I) {
386 switch (Opcode) {
387 default: assert(0 && "Unknown instruction type encountered!");
388 abort();
389 // Build the switch statement using the Instruction.def file.
390#define HANDLE_INST(NUM, OPCODE, CLASS) \
391 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
392#include "llvm/Instruction.def"
393 }
394 }
395
396 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
397
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000398 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
399 SDOperand SrcValue, SDOperand Root,
400 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000401
402 SDOperand getIntPtrConstant(uint64_t Val) {
403 return DAG.getConstant(Val, TLI.getPointerTy());
404 }
405
Chris Lattner199862b2006-03-16 19:57:50 +0000406 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000407
408 const SDOperand &setValue(const Value *V, SDOperand NewN) {
409 SDOperand &N = NodeMap[V];
410 assert(N.Val == 0 && "Already set a value for this node!");
411 return N = NewN;
412 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000413
Chris Lattner864635a2006-02-22 22:37:12 +0000414 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
415 MVT::ValueType VT,
416 bool OutReg, bool InReg,
417 std::set<unsigned> &OutputRegs,
418 std::set<unsigned> &InputRegs);
419
Chris Lattner1c08c712005-01-07 07:47:53 +0000420 // Terminator instructions.
421 void visitRet(ReturnInst &I);
422 void visitBr(BranchInst &I);
423 void visitUnreachable(UnreachableInst &I) { /* noop */ }
424
425 // These all get lowered before this pass.
Robert Bocchinoc0f4cd92006-01-10 19:04:57 +0000426 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino4eb2e3a2006-01-17 20:06:42 +0000427 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000428 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
429 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
430 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
431
432 //
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000433 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000434 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000435 void visitAdd(User &I) {
436 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000437 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000438 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000439 void visitMul(User &I) {
440 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000441 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000442 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000443 const Type *Ty = I.getType();
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000444 visitBinary(I,
445 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
446 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner1c08c712005-01-07 07:47:53 +0000447 }
448 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000449 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000450 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000451 }
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000452 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
453 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
454 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begemane21ea612005-11-18 07:42:56 +0000455 void visitShl(User &I) { visitShift(I, ISD::SHL); }
456 void visitShr(User &I) {
457 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000458 }
459
460 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
461 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
462 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
463 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
464 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
465 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
466 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
467
468 void visitGetElementPtr(User &I);
469 void visitCast(User &I);
470 void visitSelect(User &I);
471 //
472
473 void visitMalloc(MallocInst &I);
474 void visitFree(FreeInst &I);
475 void visitAlloca(AllocaInst &I);
476 void visitLoad(LoadInst &I);
477 void visitStore(StoreInst &I);
478 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
479 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000480 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000481 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000482
Chris Lattner1c08c712005-01-07 07:47:53 +0000483 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000484 void visitVAArg(VAArgInst &I);
485 void visitVAEnd(CallInst &I);
486 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000487 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000488
Chris Lattner7041ee32005-01-11 05:56:49 +0000489 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000490
491 void visitUserOp1(Instruction &I) {
492 assert(0 && "UserOp1 should not exist at instruction selection time!");
493 abort();
494 }
495 void visitUserOp2(Instruction &I) {
496 assert(0 && "UserOp2 should not exist at instruction selection time!");
497 abort();
498 }
499};
500} // end namespace llvm
501
Chris Lattner199862b2006-03-16 19:57:50 +0000502SDOperand SelectionDAGLowering::getValue(const Value *V) {
503 SDOperand &N = NodeMap[V];
504 if (N.Val) return N;
505
506 const Type *VTy = V->getType();
507 MVT::ValueType VT = TLI.getValueType(VTy);
508 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
509 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
510 visit(CE->getOpcode(), *CE);
511 assert(N.Val && "visit didn't populate the ValueMap!");
512 return N;
513 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
514 return N = DAG.getGlobalAddress(GV, VT);
515 } else if (isa<ConstantPointerNull>(C)) {
516 return N = DAG.getConstant(0, TLI.getPointerTy());
517 } else if (isa<UndefValue>(C)) {
518 return N = DAG.getNode(ISD::UNDEF, VT);
519 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
520 return N = DAG.getConstantFP(CFP->getValue(), VT);
521 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
522 unsigned NumElements = PTy->getNumElements();
523 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
524 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
525
526 // Now that we know the number and type of the elements, push a
527 // Constant or ConstantFP node onto the ops list for each element of
528 // the packed constant.
529 std::vector<SDOperand> Ops;
530 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
531 if (MVT::isFloatingPoint(PVT)) {
532 for (unsigned i = 0; i != NumElements; ++i) {
533 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
534 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
535 }
536 } else {
537 for (unsigned i = 0; i != NumElements; ++i) {
538 const ConstantIntegral *El =
539 cast<ConstantIntegral>(CP->getOperand(i));
540 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
541 }
542 }
543 } else {
544 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
545 SDOperand Op;
546 if (MVT::isFloatingPoint(PVT))
547 Op = DAG.getConstantFP(0, PVT);
548 else
549 Op = DAG.getConstant(0, PVT);
550 Ops.assign(NumElements, Op);
551 }
552
553 // Handle the case where we have a 1-element vector, in which
554 // case we want to immediately turn it into a scalar constant.
555 if (Ops.size() == 1) {
556 return N = Ops[0];
557 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
558 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
559 } else {
560 // If the packed type isn't legal, then create a ConstantVec node with
561 // generic Vector type instead.
562 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
563 SDOperand Typ = DAG.getValueType(PVT);
564 Ops.insert(Ops.begin(), Typ);
565 Ops.insert(Ops.begin(), Num);
566 return N = DAG.getNode(ISD::VConstant, MVT::Vector, Ops);
567 }
568 } else {
569 // Canonicalize all constant ints to be unsigned.
570 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
571 }
572 }
573
574 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
575 std::map<const AllocaInst*, int>::iterator SI =
576 FuncInfo.StaticAllocaMap.find(AI);
577 if (SI != FuncInfo.StaticAllocaMap.end())
578 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
579 }
580
581 std::map<const Value*, unsigned>::const_iterator VMI =
582 FuncInfo.ValueMap.find(V);
583 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
584
585 unsigned InReg = VMI->second;
586
587 // If this type is not legal, make it so now.
588 if (VT == MVT::Vector) {
589 // FIXME: We only handle legal vectors right now. We need a VBUILD_VECTOR
590 const PackedType *PTy = cast<PackedType>(VTy);
591 unsigned NumElements = PTy->getNumElements();
592 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
593 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
594 assert(TLI.isTypeLegal(TVT) &&
595 "FIXME: Cannot handle illegal vector types here yet!");
596 VT = TVT;
597 }
598
599 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
600
601 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
602 if (DestVT < VT) {
603 // Source must be expanded. This input value is actually coming from the
604 // register pair VMI->second and VMI->second+1.
605 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
606 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
607 } else {
608 if (DestVT > VT) { // Promotion case
609 if (MVT::isFloatingPoint(VT))
610 N = DAG.getNode(ISD::FP_ROUND, VT, N);
611 else
612 N = DAG.getNode(ISD::TRUNCATE, VT, N);
613 }
614 }
615
616 return N;
617}
618
619
Chris Lattner1c08c712005-01-07 07:47:53 +0000620void SelectionDAGLowering::visitRet(ReturnInst &I) {
621 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000622 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000623 return;
624 }
Nate Begemanee625572006-01-27 21:09:22 +0000625 std::vector<SDOperand> NewValues;
626 NewValues.push_back(getRoot());
627 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
628 SDOperand RetOp = getValue(I.getOperand(i));
629
630 // If this is an integer return value, we need to promote it ourselves to
631 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
632 // than sign/zero.
633 if (MVT::isInteger(RetOp.getValueType()) &&
634 RetOp.getValueType() < MVT::i64) {
635 MVT::ValueType TmpVT;
636 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
637 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
638 else
639 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000640
Nate Begemanee625572006-01-27 21:09:22 +0000641 if (I.getOperand(i)->getType()->isSigned())
642 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
643 else
644 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
645 }
646 NewValues.push_back(RetOp);
Chris Lattner1c08c712005-01-07 07:47:53 +0000647 }
Nate Begemanee625572006-01-27 21:09:22 +0000648 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner1c08c712005-01-07 07:47:53 +0000649}
650
651void SelectionDAGLowering::visitBr(BranchInst &I) {
652 // Update machine-CFG edges.
653 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000654
655 // Figure out which block is immediately after the current one.
656 MachineBasicBlock *NextBlock = 0;
657 MachineFunction::iterator BBI = CurMBB;
658 if (++BBI != CurMBB->getParent()->end())
659 NextBlock = BBI;
660
661 if (I.isUnconditional()) {
662 // If this is not a fall-through branch, emit the branch.
663 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000664 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000665 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000666 } else {
667 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000668
669 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000670 if (Succ1MBB == NextBlock) {
671 // If the condition is false, fall through. This means we should branch
672 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000673 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000674 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000675 } else if (Succ0MBB == NextBlock) {
676 // If the condition is true, fall through. This means we should branch if
677 // the condition is false to Succ #1. Invert the condition first.
678 SDOperand True = DAG.getConstant(1, Cond.getValueType());
679 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000680 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000681 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000682 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000683 std::vector<SDOperand> Ops;
684 Ops.push_back(getRoot());
Evan Cheng298ebf22006-02-16 08:27:56 +0000685 // If the false case is the current basic block, then this is a self
686 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
687 // adds an extra instruction in the loop. Instead, invert the
688 // condition and emit "Loop: ... br!cond Loop; br Out.
689 if (CurMBB == Succ1MBB) {
690 std::swap(Succ0MBB, Succ1MBB);
691 SDOperand True = DAG.getConstant(1, Cond.getValueType());
692 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
693 }
Nate Begeman81e80972006-03-17 01:40:33 +0000694 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
695 DAG.getBasicBlock(Succ0MBB));
696 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
697 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000698 }
699 }
700}
701
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000702void SelectionDAGLowering::visitSub(User &I) {
703 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +0000704 if (I.getType()->isFloatingPoint()) {
705 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
706 if (CFP->isExactlyValue(-0.0)) {
707 SDOperand Op2 = getValue(I.getOperand(1));
708 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
709 return;
710 }
Chris Lattner01b3d732005-09-28 22:28:18 +0000711 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000712 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000713}
714
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000715void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
716 unsigned VecOp) {
717 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +0000718 SDOperand Op1 = getValue(I.getOperand(0));
719 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000720
Chris Lattnerb67eb912005-11-19 18:40:42 +0000721 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000722 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
723 } else if (Ty->isFloatingPoint()) {
724 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
725 } else {
726 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000727 unsigned NumElements = PTy->getNumElements();
728 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000729 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000730
731 // Immediately scalarize packed types containing only one element, so that
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000732 // the Legalize pass does not have to deal with them. Similarly, if the
733 // abstract vector is going to turn into one that the target natively
734 // supports, generate that type now so that Legalize doesn't have to deal
735 // with that either. These steps ensure that Legalize only has to handle
736 // vector types in its Expand case.
737 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman4ef3b812005-11-22 01:29:36 +0000738 if (NumElements == 1) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000739 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Evan Cheng860771d2006-03-01 01:09:54 +0000740 } else if (TVT != MVT::Other &&
741 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(Opc, TVT)) {
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000742 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000743 } else {
744 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
745 SDOperand Typ = DAG.getValueType(PVT);
Evan Cheng860771d2006-03-01 01:09:54 +0000746 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Num, Typ, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000747 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000748 }
Nate Begemane21ea612005-11-18 07:42:56 +0000749}
Chris Lattner2c49f272005-01-19 22:31:21 +0000750
Nate Begemane21ea612005-11-18 07:42:56 +0000751void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
752 SDOperand Op1 = getValue(I.getOperand(0));
753 SDOperand Op2 = getValue(I.getOperand(1));
754
755 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
756
Chris Lattner1c08c712005-01-07 07:47:53 +0000757 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
758}
759
760void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
761 ISD::CondCode UnsignedOpcode) {
762 SDOperand Op1 = getValue(I.getOperand(0));
763 SDOperand Op2 = getValue(I.getOperand(1));
764 ISD::CondCode Opcode = SignedOpcode;
765 if (I.getOperand(0)->getType()->isUnsigned())
766 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000767 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000768}
769
770void SelectionDAGLowering::visitSelect(User &I) {
771 SDOperand Cond = getValue(I.getOperand(0));
772 SDOperand TrueVal = getValue(I.getOperand(1));
773 SDOperand FalseVal = getValue(I.getOperand(2));
774 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
775 TrueVal, FalseVal));
776}
777
778void SelectionDAGLowering::visitCast(User &I) {
779 SDOperand N = getValue(I.getOperand(0));
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000780 MVT::ValueType SrcVT = TLI.getValueType(I.getOperand(0)->getType());
781 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner1c08c712005-01-07 07:47:53 +0000782
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000783 if (N.getValueType() == DestVT) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000784 setValue(&I, N); // noop cast.
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000785 } else if (DestVT == MVT::i1) {
Chris Lattneref311aa2005-05-09 22:17:13 +0000786 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000787 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattneref311aa2005-05-09 22:17:13 +0000788 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000789 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000790 } else if (isInteger(SrcVT)) {
791 if (isInteger(DestVT)) { // Int -> Int cast
792 if (DestVT < SrcVT) // Truncating cast?
793 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000794 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000795 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000796 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000797 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000798 } else { // Int -> FP cast
799 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000800 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000801 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000802 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000803 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000804 } else if (isFloatingPoint(SrcVT)) {
805 if (isFloatingPoint(DestVT)) { // FP -> FP cast
806 if (DestVT < SrcVT) // Rounding cast?
807 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000808 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000809 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000810 } else { // FP -> Int cast.
811 if (I.getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000812 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000813 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000814 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
815 }
816 } else {
817 const PackedType *SrcTy = cast<PackedType>(I.getOperand(0)->getType());
818 const PackedType *DstTy = cast<PackedType>(I.getType());
819
820 unsigned SrcNumElements = SrcTy->getNumElements();
821 MVT::ValueType SrcPVT = TLI.getValueType(SrcTy->getElementType());
822 MVT::ValueType SrcTVT = MVT::getVectorType(SrcPVT, SrcNumElements);
823
824 unsigned DstNumElements = DstTy->getNumElements();
825 MVT::ValueType DstPVT = TLI.getValueType(DstTy->getElementType());
826 MVT::ValueType DstTVT = MVT::getVectorType(DstPVT, DstNumElements);
827
828 // If the input and output type are legal, convert this to a bit convert of
829 // the SrcTVT/DstTVT types.
830 if (SrcTVT != MVT::Other && DstTVT != MVT::Other &&
831 TLI.isTypeLegal(SrcTVT) && TLI.isTypeLegal(DstTVT)) {
832 assert(N.getValueType() == SrcTVT);
833 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DstTVT, N));
834 } else {
835 // Otherwise, convert this directly into a store/load.
836 // FIXME: add a VBIT_CONVERT node that we could use to automatically turn
837 // 8xFloat -> 8xInt casts into two 4xFloat -> 4xInt casts.
838 // Create the stack frame object.
839 uint64_t ByteSize = TD.getTypeSize(SrcTy);
840 assert(ByteSize == TD.getTypeSize(DstTy) && "Not a bit_convert!");
841 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
842 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
843 SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
844
845 // Emit a store to the stack slot.
846 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
847 N, FIPtr, DAG.getSrcValue(NULL));
848 // Result is a load from the stack slot.
849 SDOperand Val =
850 getLoadFrom(DstTy, FIPtr, DAG.getSrcValue(NULL), Store, false);
851 setValue(&I, Val);
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000852 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000853 }
854}
855
856void SelectionDAGLowering::visitGetElementPtr(User &I) {
857 SDOperand N = getValue(I.getOperand(0));
858 const Type *Ty = I.getOperand(0)->getType();
859 const Type *UIntPtrTy = TD.getIntPtrType();
860
861 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
862 OI != E; ++OI) {
863 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +0000864 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000865 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
866 if (Field) {
867 // N = N + Offset
868 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
869 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000870 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000871 }
872 Ty = StTy->getElementType(Field);
873 } else {
874 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +0000875
Chris Lattner7c0104b2005-11-09 04:45:33 +0000876 // If this is a constant subscript, handle it quickly.
877 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
878 if (CI->getRawValue() == 0) continue;
Chris Lattner7cc47772005-01-07 21:56:57 +0000879
Chris Lattner7c0104b2005-11-09 04:45:33 +0000880 uint64_t Offs;
881 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
882 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
883 else
884 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
885 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
886 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +0000887 }
Chris Lattner7c0104b2005-11-09 04:45:33 +0000888
889 // N = N + Idx * ElementSize;
890 uint64_t ElementSize = TD.getTypeSize(Ty);
891 SDOperand IdxN = getValue(Idx);
892
893 // If the index is smaller or larger than intptr_t, truncate or extend
894 // it.
895 if (IdxN.getValueType() < N.getValueType()) {
896 if (Idx->getType()->isSigned())
897 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
898 else
899 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
900 } else if (IdxN.getValueType() > N.getValueType())
901 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
902
903 // If this is a multiply by a power of two, turn it into a shl
904 // immediately. This is a very common case.
905 if (isPowerOf2_64(ElementSize)) {
906 unsigned Amt = Log2_64(ElementSize);
907 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +0000908 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +0000909 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
910 continue;
911 }
912
913 SDOperand Scale = getIntPtrConstant(ElementSize);
914 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
915 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +0000916 }
917 }
918 setValue(&I, N);
919}
920
921void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
922 // If this is a fixed sized alloca in the entry block of the function,
923 // allocate it statically on the stack.
924 if (FuncInfo.StaticAllocaMap.count(&I))
925 return; // getValue will auto-populate this.
926
927 const Type *Ty = I.getAllocatedType();
928 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000929 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
930 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +0000931
932 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000933 MVT::ValueType IntPtr = TLI.getPointerTy();
934 if (IntPtr < AllocSize.getValueType())
935 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
936 else if (IntPtr > AllocSize.getValueType())
937 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000938
Chris Lattner68cd65e2005-01-22 23:04:37 +0000939 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000940 getIntPtrConstant(TySize));
941
942 // Handle alignment. If the requested alignment is less than or equal to the
943 // stack alignment, ignore it and round the size of the allocation up to the
944 // stack alignment size. If the size is greater than the stack alignment, we
945 // note this in the DYNAMIC_STACKALLOC node.
946 unsigned StackAlign =
947 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
948 if (Align <= StackAlign) {
949 Align = 0;
950 // Add SA-1 to the size.
951 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
952 getIntPtrConstant(StackAlign-1));
953 // Mask out the low bits for alignment purposes.
954 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
955 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
956 }
957
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000958 std::vector<MVT::ValueType> VTs;
959 VTs.push_back(AllocSize.getValueType());
960 VTs.push_back(MVT::Other);
961 std::vector<SDOperand> Ops;
962 Ops.push_back(getRoot());
963 Ops.push_back(AllocSize);
964 Ops.push_back(getIntPtrConstant(Align));
965 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000966 DAG.setRoot(setValue(&I, DSA).getValue(1));
967
968 // Inform the Frame Information that we have just allocated a variable-sized
969 // object.
970 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
971}
972
Chris Lattner1c08c712005-01-07 07:47:53 +0000973void SelectionDAGLowering::visitLoad(LoadInst &I) {
974 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000975
Chris Lattnerd3948112005-01-17 22:19:26 +0000976 SDOperand Root;
977 if (I.isVolatile())
978 Root = getRoot();
979 else {
980 // Do not serialize non-volatile loads against each other.
981 Root = DAG.getRoot();
982 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000983
984 setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
985 Root, I.isVolatile()));
986}
987
988SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
989 SDOperand SrcValue, SDOperand Root,
990 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000991 SDOperand L;
992
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000993 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000994 unsigned NumElements = PTy->getNumElements();
995 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000996 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000997
998 // Immediately scalarize packed types containing only one element, so that
999 // the Legalize pass does not have to deal with them.
1000 if (NumElements == 1) {
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001001 L = DAG.getLoad(PVT, Root, Ptr, SrcValue);
1002 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT) &&
1003 TLI.isOperationLegal(ISD::LOAD, TVT)) {
1004 L = DAG.getLoad(TVT, Root, Ptr, SrcValue);
Nate Begeman4ef3b812005-11-22 01:29:36 +00001005 } else {
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001006 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr, SrcValue);
Nate Begeman4ef3b812005-11-22 01:29:36 +00001007 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001008 } else {
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001009 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001010 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001011
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001012 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001013 DAG.setRoot(L.getValue(1));
1014 else
1015 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001016
1017 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001018}
1019
1020
1021void SelectionDAGLowering::visitStore(StoreInst &I) {
1022 Value *SrcV = I.getOperand(0);
1023 SDOperand Src = getValue(SrcV);
1024 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +00001025 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +00001026 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001027}
1028
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001029/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1030/// we want to emit this as a call to a named external function, return the name
1031/// otherwise lower it and return null.
1032const char *
1033SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1034 switch (Intrinsic) {
1035 case Intrinsic::vastart: visitVAStart(I); return 0;
1036 case Intrinsic::vaend: visitVAEnd(I); return 0;
1037 case Intrinsic::vacopy: visitVACopy(I); return 0;
1038 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1039 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1040 case Intrinsic::setjmp:
1041 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1042 break;
1043 case Intrinsic::longjmp:
1044 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1045 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001046 case Intrinsic::memcpy_i32:
1047 case Intrinsic::memcpy_i64:
1048 visitMemIntrinsic(I, ISD::MEMCPY);
1049 return 0;
1050 case Intrinsic::memset_i32:
1051 case Intrinsic::memset_i64:
1052 visitMemIntrinsic(I, ISD::MEMSET);
1053 return 0;
1054 case Intrinsic::memmove_i32:
1055 case Intrinsic::memmove_i64:
1056 visitMemIntrinsic(I, ISD::MEMMOVE);
1057 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001058
Chris Lattner86cb6432005-12-13 17:40:33 +00001059 case Intrinsic::dbg_stoppoint: {
Jim Laskeyce72b172006-02-11 01:01:30 +00001060 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeyf4321a32006-03-13 13:07:37 +00001061 if (DebugInfo && DebugInfo->Verify(I.getOperand(3))) {
Jim Laskeyce72b172006-02-11 01:01:30 +00001062 std::vector<SDOperand> Ops;
Chris Lattner36ce6912005-11-29 06:21:05 +00001063
Jim Laskeyce72b172006-02-11 01:01:30 +00001064 // Input Chain
1065 Ops.push_back(getRoot());
1066
1067 // line number
Jim Laskeyf4321a32006-03-13 13:07:37 +00001068 Ops.push_back(getValue(I.getOperand(1)));
Jim Laskeyce72b172006-02-11 01:01:30 +00001069
1070 // column
Jim Laskeyf4321a32006-03-13 13:07:37 +00001071 Ops.push_back(getValue(I.getOperand(2)));
Chris Lattner36ce6912005-11-29 06:21:05 +00001072
Jim Laskeyf4321a32006-03-13 13:07:37 +00001073 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(3));
Jim Laskeyce72b172006-02-11 01:01:30 +00001074 assert(DD && "Not a debug information descriptor");
1075 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
1076 assert(CompileUnit && "Not a compile unit");
1077 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1078 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1079
1080 if (Ops.size() == 5) // Found filename/workingdir.
1081 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner86cb6432005-12-13 17:40:33 +00001082 }
1083
Chris Lattnerd67b3a82005-12-03 18:50:48 +00001084 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001085 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00001086 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001087 case Intrinsic::dbg_region_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001088 if (I.getType() != Type::VoidTy)
1089 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1090 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001091 case Intrinsic::dbg_region_end:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001092 if (I.getType() != Type::VoidTy)
1093 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1094 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001095 case Intrinsic::dbg_func_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001096 if (I.getType() != Type::VoidTy)
1097 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1098 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001099
Reid Spencer0b118202006-01-16 21:12:35 +00001100 case Intrinsic::isunordered_f32:
1101 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001102 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1103 getValue(I.getOperand(2)), ISD::SETUO));
1104 return 0;
1105
Reid Spencer0b118202006-01-16 21:12:35 +00001106 case Intrinsic::sqrt_f32:
1107 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001108 setValue(&I, DAG.getNode(ISD::FSQRT,
1109 getValue(I.getOperand(1)).getValueType(),
1110 getValue(I.getOperand(1))));
1111 return 0;
1112 case Intrinsic::pcmarker: {
1113 SDOperand Tmp = getValue(I.getOperand(1));
1114 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1115 return 0;
1116 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001117 case Intrinsic::readcyclecounter: {
1118 std::vector<MVT::ValueType> VTs;
1119 VTs.push_back(MVT::i64);
1120 VTs.push_back(MVT::Other);
1121 std::vector<SDOperand> Ops;
1122 Ops.push_back(getRoot());
1123 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1124 setValue(&I, Tmp);
1125 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001126 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001127 }
Nate Begemand88fc032006-01-14 03:14:10 +00001128 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001129 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001130 case Intrinsic::bswap_i64:
1131 setValue(&I, DAG.getNode(ISD::BSWAP,
1132 getValue(I.getOperand(1)).getValueType(),
1133 getValue(I.getOperand(1))));
1134 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001135 case Intrinsic::cttz_i8:
1136 case Intrinsic::cttz_i16:
1137 case Intrinsic::cttz_i32:
1138 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001139 setValue(&I, DAG.getNode(ISD::CTTZ,
1140 getValue(I.getOperand(1)).getValueType(),
1141 getValue(I.getOperand(1))));
1142 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001143 case Intrinsic::ctlz_i8:
1144 case Intrinsic::ctlz_i16:
1145 case Intrinsic::ctlz_i32:
1146 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001147 setValue(&I, DAG.getNode(ISD::CTLZ,
1148 getValue(I.getOperand(1)).getValueType(),
1149 getValue(I.getOperand(1))));
1150 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001151 case Intrinsic::ctpop_i8:
1152 case Intrinsic::ctpop_i16:
1153 case Intrinsic::ctpop_i32:
1154 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001155 setValue(&I, DAG.getNode(ISD::CTPOP,
1156 getValue(I.getOperand(1)).getValueType(),
1157 getValue(I.getOperand(1))));
1158 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001159 case Intrinsic::stacksave: {
1160 std::vector<MVT::ValueType> VTs;
1161 VTs.push_back(TLI.getPointerTy());
1162 VTs.push_back(MVT::Other);
1163 std::vector<SDOperand> Ops;
1164 Ops.push_back(getRoot());
1165 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1166 setValue(&I, Tmp);
1167 DAG.setRoot(Tmp.getValue(1));
1168 return 0;
1169 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00001170 case Intrinsic::stackrestore: {
1171 SDOperand Tmp = getValue(I.getOperand(1));
1172 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00001173 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00001174 }
Chris Lattnerac22c832005-12-12 22:51:16 +00001175 case Intrinsic::prefetch:
1176 // FIXME: Currently discarding prefetches.
1177 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001178 default:
1179 std::cerr << I;
1180 assert(0 && "This intrinsic is not implemented yet!");
1181 return 0;
1182 }
1183}
1184
1185
Chris Lattner1c08c712005-01-07 07:47:53 +00001186void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001187 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001188 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001189 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001190 if (unsigned IID = F->getIntrinsicID()) {
1191 RenameFn = visitIntrinsicCall(I, IID);
1192 if (!RenameFn)
1193 return;
1194 } else { // Not an LLVM intrinsic.
1195 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00001196 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1197 if (I.getNumOperands() == 3 && // Basic sanity checks.
1198 I.getOperand(1)->getType()->isFloatingPoint() &&
1199 I.getType() == I.getOperand(1)->getType() &&
1200 I.getType() == I.getOperand(2)->getType()) {
1201 SDOperand LHS = getValue(I.getOperand(1));
1202 SDOperand RHS = getValue(I.getOperand(2));
1203 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1204 LHS, RHS));
1205 return;
1206 }
1207 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001208 if (I.getNumOperands() == 2 && // Basic sanity checks.
1209 I.getOperand(1)->getType()->isFloatingPoint() &&
1210 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001211 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001212 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1213 return;
1214 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001215 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001216 if (I.getNumOperands() == 2 && // Basic sanity checks.
1217 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001218 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001219 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001220 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1221 return;
1222 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001223 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001224 if (I.getNumOperands() == 2 && // Basic sanity checks.
1225 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001226 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001227 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001228 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1229 return;
1230 }
1231 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001232 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001233 } else if (isa<InlineAsm>(I.getOperand(0))) {
1234 visitInlineAsm(I);
1235 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001236 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001237
Chris Lattner64e14b12005-01-08 22:48:57 +00001238 SDOperand Callee;
1239 if (!RenameFn)
1240 Callee = getValue(I.getOperand(0));
1241 else
1242 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001243 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001244 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001245 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1246 Value *Arg = I.getOperand(i);
1247 SDOperand ArgNode = getValue(Arg);
1248 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1249 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001250
Nate Begeman8e21e712005-03-26 01:29:23 +00001251 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1252 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001253
Chris Lattnercf5734d2005-01-08 19:26:18 +00001254 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001255 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001256 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001257 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001258 setValue(&I, Result.first);
1259 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001260}
1261
Chris Lattner864635a2006-02-22 22:37:12 +00001262SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001263 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00001264 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1265 Chain = Val.getValue(1);
1266 Flag = Val.getValue(2);
1267
1268 // If the result was expanded, copy from the top part.
1269 if (Regs.size() > 1) {
1270 assert(Regs.size() == 2 &&
1271 "Cannot expand to more than 2 elts yet!");
1272 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1273 Chain = Val.getValue(1);
1274 Flag = Val.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00001275 if (DAG.getTargetLoweringInfo().isLittleEndian())
1276 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1277 else
1278 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00001279 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00001280
Chris Lattner864635a2006-02-22 22:37:12 +00001281 // Otherwise, if the return value was promoted, truncate it to the
1282 // appropriate type.
1283 if (RegVT == ValueVT)
1284 return Val;
1285
1286 if (MVT::isInteger(RegVT))
1287 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1288 else
1289 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1290}
1291
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001292/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1293/// specified value into the registers specified by this object. This uses
1294/// Chain/Flag as the input and updates them for the output Chain/Flag.
1295void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001296 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001297 if (Regs.size() == 1) {
1298 // If there is a single register and the types differ, this must be
1299 // a promotion.
1300 if (RegVT != ValueVT) {
1301 if (MVT::isInteger(RegVT))
1302 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1303 else
1304 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1305 }
1306 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1307 Flag = Chain.getValue(1);
1308 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00001309 std::vector<unsigned> R(Regs);
1310 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1311 std::reverse(R.begin(), R.end());
1312
1313 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001314 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1315 DAG.getConstant(i, MVT::i32));
Chris Lattner9f6637d2006-02-23 20:06:57 +00001316 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001317 Flag = Chain.getValue(1);
1318 }
1319 }
1320}
Chris Lattner864635a2006-02-22 22:37:12 +00001321
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001322/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1323/// operand list. This adds the code marker and includes the number of
1324/// values added into it.
1325void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001326 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001327 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1328 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1329 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1330}
Chris Lattner864635a2006-02-22 22:37:12 +00001331
1332/// isAllocatableRegister - If the specified register is safe to allocate,
1333/// i.e. it isn't a stack pointer or some other special register, return the
1334/// register class for the register. Otherwise, return null.
1335static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001336isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1337 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1338 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1339 E = MRI->regclass_end(); RCI != E; ++RCI) {
1340 const TargetRegisterClass *RC = *RCI;
1341 // If none of the the value types for this register class are valid, we
1342 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1343 bool isLegal = false;
1344 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1345 I != E; ++I) {
1346 if (TLI.isTypeLegal(*I)) {
1347 isLegal = true;
1348 break;
1349 }
1350 }
1351
1352 if (!isLegal) continue;
1353
Chris Lattner864635a2006-02-22 22:37:12 +00001354 // NOTE: This isn't ideal. In particular, this might allocate the
1355 // frame pointer in functions that need it (due to them not being taken
1356 // out of allocation, because a variable sized allocation hasn't been seen
1357 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001358 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1359 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner864635a2006-02-22 22:37:12 +00001360 if (*I == Reg)
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001361 return RC;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001362 }
1363 return 0;
Chris Lattner864635a2006-02-22 22:37:12 +00001364}
1365
1366RegsForValue SelectionDAGLowering::
1367GetRegistersForValue(const std::string &ConstrCode,
1368 MVT::ValueType VT, bool isOutReg, bool isInReg,
1369 std::set<unsigned> &OutputRegs,
1370 std::set<unsigned> &InputRegs) {
1371 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1372 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1373 std::vector<unsigned> Regs;
1374
1375 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1376 MVT::ValueType RegVT;
1377 MVT::ValueType ValueVT = VT;
1378
1379 if (PhysReg.first) {
1380 if (VT == MVT::Other)
1381 ValueVT = *PhysReg.second->vt_begin();
1382 RegVT = VT;
1383
1384 // This is a explicit reference to a physical register.
1385 Regs.push_back(PhysReg.first);
1386
1387 // If this is an expanded reference, add the rest of the regs to Regs.
1388 if (NumRegs != 1) {
1389 RegVT = *PhysReg.second->vt_begin();
1390 TargetRegisterClass::iterator I = PhysReg.second->begin();
1391 TargetRegisterClass::iterator E = PhysReg.second->end();
1392 for (; *I != PhysReg.first; ++I)
1393 assert(I != E && "Didn't find reg!");
1394
1395 // Already added the first reg.
1396 --NumRegs; ++I;
1397 for (; NumRegs; --NumRegs, ++I) {
1398 assert(I != E && "Ran out of registers to allocate!");
1399 Regs.push_back(*I);
1400 }
1401 }
1402 return RegsForValue(Regs, RegVT, ValueVT);
1403 }
1404
1405 // This is a reference to a register class. Allocate NumRegs consecutive,
1406 // available, registers from the class.
1407 std::vector<unsigned> RegClassRegs =
1408 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1409
1410 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1411 MachineFunction &MF = *CurMBB->getParent();
1412 unsigned NumAllocated = 0;
1413 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1414 unsigned Reg = RegClassRegs[i];
1415 // See if this register is available.
1416 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1417 (isInReg && InputRegs.count(Reg))) { // Already used.
1418 // Make sure we find consecutive registers.
1419 NumAllocated = 0;
1420 continue;
1421 }
1422
1423 // Check to see if this register is allocatable (i.e. don't give out the
1424 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001425 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00001426 if (!RC) {
1427 // Make sure we find consecutive registers.
1428 NumAllocated = 0;
1429 continue;
1430 }
1431
1432 // Okay, this register is good, we can use it.
1433 ++NumAllocated;
1434
1435 // If we allocated enough consecutive
1436 if (NumAllocated == NumRegs) {
1437 unsigned RegStart = (i-NumAllocated)+1;
1438 unsigned RegEnd = i+1;
1439 // Mark all of the allocated registers used.
1440 for (unsigned i = RegStart; i != RegEnd; ++i) {
1441 unsigned Reg = RegClassRegs[i];
1442 Regs.push_back(Reg);
1443 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1444 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1445 }
1446
1447 return RegsForValue(Regs, *RC->vt_begin(), VT);
1448 }
1449 }
1450
1451 // Otherwise, we couldn't allocate enough registers for this.
1452 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00001453}
1454
Chris Lattner864635a2006-02-22 22:37:12 +00001455
Chris Lattnerce7518c2006-01-26 22:24:51 +00001456/// visitInlineAsm - Handle a call to an InlineAsm object.
1457///
1458void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1459 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1460
1461 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1462 MVT::Other);
1463
1464 // Note, we treat inline asms both with and without side-effects as the same.
1465 // If an inline asm doesn't have side effects and doesn't access memory, we
1466 // could not choose to not chain it.
1467 bool hasSideEffects = IA->hasSideEffects();
1468
Chris Lattner2cc2f662006-02-01 01:28:23 +00001469 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001470 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00001471
1472 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1473 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1474 /// if it is a def of that register.
1475 std::vector<SDOperand> AsmNodeOperands;
1476 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1477 AsmNodeOperands.push_back(AsmStr);
1478
1479 SDOperand Chain = getRoot();
1480 SDOperand Flag;
1481
Chris Lattner4e4b5762006-02-01 18:59:47 +00001482 // We fully assign registers here at isel time. This is not optimal, but
1483 // should work. For register classes that correspond to LLVM classes, we
1484 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1485 // over the constraints, collecting fixed registers that we know we can't use.
1486 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001487 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001488 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1489 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1490 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00001491
Chris Lattner1efa40f2006-02-22 00:56:39 +00001492 MVT::ValueType OpVT;
1493
1494 // Compute the value type for each operand and add it to ConstraintVTs.
1495 switch (Constraints[i].Type) {
1496 case InlineAsm::isOutput:
1497 if (!Constraints[i].isIndirectOutput) {
1498 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1499 OpVT = TLI.getValueType(I.getType());
1500 } else {
Chris Lattner22873462006-02-27 23:45:39 +00001501 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001502 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1503 OpNum++; // Consumes a call operand.
1504 }
1505 break;
1506 case InlineAsm::isInput:
1507 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1508 OpNum++; // Consumes a call operand.
1509 break;
1510 case InlineAsm::isClobber:
1511 OpVT = MVT::Other;
1512 break;
1513 }
1514
1515 ConstraintVTs.push_back(OpVT);
1516
Chris Lattner864635a2006-02-22 22:37:12 +00001517 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1518 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00001519
Chris Lattner864635a2006-02-22 22:37:12 +00001520 // Build a list of regs that this operand uses. This always has a single
1521 // element for promoted/expanded operands.
1522 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1523 false, false,
1524 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00001525
1526 switch (Constraints[i].Type) {
1527 case InlineAsm::isOutput:
1528 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001529 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001530 // If this is an early-clobber output, it cannot be assigned to the same
1531 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00001532 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00001533 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001534 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001535 case InlineAsm::isInput:
1536 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001537 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00001538 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001539 case InlineAsm::isClobber:
1540 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00001541 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1542 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001543 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001544 }
1545 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00001546
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001547 // Loop over all of the inputs, copying the operand values into the
1548 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00001549 RegsForValue RetValRegs;
1550 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001551 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001552
Chris Lattner6656dd12006-01-31 02:03:41 +00001553 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00001554 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1555 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00001556
Chris Lattner2cc2f662006-02-01 01:28:23 +00001557 switch (Constraints[i].Type) {
1558 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00001559 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1560 if (ConstraintCode.size() == 1) // not a physreg name.
1561 CTy = TLI.getConstraintType(ConstraintCode[0]);
1562
1563 if (CTy == TargetLowering::C_Memory) {
1564 // Memory output.
1565 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1566
1567 // Check that the operand (the address to store to) isn't a float.
1568 if (!MVT::isInteger(InOperandVal.getValueType()))
1569 assert(0 && "MATCH FAIL!");
1570
1571 if (!Constraints[i].isIndirectOutput)
1572 assert(0 && "MATCH FAIL!");
1573
1574 OpNum++; // Consumes a call operand.
1575
1576 // Extend/truncate to the right pointer type if needed.
1577 MVT::ValueType PtrType = TLI.getPointerTy();
1578 if (InOperandVal.getValueType() < PtrType)
1579 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1580 else if (InOperandVal.getValueType() > PtrType)
1581 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1582
1583 // Add information to the INLINEASM node to know about this output.
1584 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1585 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1586 AsmNodeOperands.push_back(InOperandVal);
1587 break;
1588 }
1589
1590 // Otherwise, this is a register output.
1591 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1592
Chris Lattner864635a2006-02-22 22:37:12 +00001593 // If this is an early-clobber output, or if there is an input
1594 // constraint that matches this, we need to reserve the input register
1595 // so no other inputs allocate to it.
1596 bool UsesInputRegister = false;
1597 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1598 UsesInputRegister = true;
1599
1600 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00001601 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00001602 RegsForValue Regs =
1603 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1604 true, UsesInputRegister,
1605 OutputRegs, InputRegs);
1606 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner1efa40f2006-02-22 00:56:39 +00001607
Chris Lattner2cc2f662006-02-01 01:28:23 +00001608 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00001609 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00001610 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00001611 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00001612 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00001613 } else {
Chris Lattner22873462006-02-27 23:45:39 +00001614 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1615 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00001616 OpNum++; // Consumes a call operand.
1617 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001618
1619 // Add information to the INLINEASM node to know that this register is
1620 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001621 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001622 break;
1623 }
1624 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00001625 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00001626 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00001627
Chris Lattner2223aea2006-02-02 00:25:23 +00001628 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1629 // If this is required to match an output register we have already set,
1630 // just use its register.
1631 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00001632
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001633 // Scan until we find the definition we already emitted of this operand.
1634 // When we find it, create a RegsForValue operand.
1635 unsigned CurOp = 2; // The first operand.
1636 for (; OperandNo; --OperandNo) {
1637 // Advance to the next operand.
1638 unsigned NumOps =
1639 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1640 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1641 "Skipped past definitions?");
1642 CurOp += (NumOps>>3)+1;
1643 }
1644
1645 unsigned NumOps =
1646 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1647 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1648 "Skipped past definitions?");
1649
1650 // Add NumOps>>3 registers to MatchedRegs.
1651 RegsForValue MatchedRegs;
1652 MatchedRegs.ValueVT = InOperandVal.getValueType();
1653 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1654 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1655 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1656 MatchedRegs.Regs.push_back(Reg);
1657 }
1658
1659 // Use the produced MatchedRegs object to
1660 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1661 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001662 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00001663 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00001664
1665 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1666 if (ConstraintCode.size() == 1) // not a physreg name.
1667 CTy = TLI.getConstraintType(ConstraintCode[0]);
1668
1669 if (CTy == TargetLowering::C_Other) {
1670 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1671 assert(0 && "MATCH FAIL!");
1672
1673 // Add information to the INLINEASM node to know about this input.
1674 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1675 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1676 AsmNodeOperands.push_back(InOperandVal);
1677 break;
1678 } else if (CTy == TargetLowering::C_Memory) {
1679 // Memory input.
1680
1681 // Check that the operand isn't a float.
1682 if (!MVT::isInteger(InOperandVal.getValueType()))
1683 assert(0 && "MATCH FAIL!");
1684
1685 // Extend/truncate to the right pointer type if needed.
1686 MVT::ValueType PtrType = TLI.getPointerTy();
1687 if (InOperandVal.getValueType() < PtrType)
1688 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1689 else if (InOperandVal.getValueType() > PtrType)
1690 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1691
1692 // Add information to the INLINEASM node to know about this input.
1693 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1694 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1695 AsmNodeOperands.push_back(InOperandVal);
1696 break;
1697 }
1698
1699 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1700
1701 // Copy the input into the appropriate registers.
1702 RegsForValue InRegs =
1703 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1704 false, true, OutputRegs, InputRegs);
1705 // FIXME: should be match fail.
1706 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1707
1708 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1709
1710 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001711 break;
1712 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001713 case InlineAsm::isClobber: {
1714 RegsForValue ClobberedRegs =
1715 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1716 OutputRegs, InputRegs);
1717 // Add the clobbered value to the operand list, so that the register
1718 // allocator is aware that the physreg got clobbered.
1719 if (!ClobberedRegs.Regs.empty())
1720 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001721 break;
1722 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001723 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001724 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001725
1726 // Finish up input operands.
1727 AsmNodeOperands[0] = Chain;
1728 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1729
1730 std::vector<MVT::ValueType> VTs;
1731 VTs.push_back(MVT::Other);
1732 VTs.push_back(MVT::Flag);
1733 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1734 Flag = Chain.getValue(1);
1735
Chris Lattner6656dd12006-01-31 02:03:41 +00001736 // If this asm returns a register value, copy the result from that register
1737 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00001738 if (!RetValRegs.Regs.empty())
1739 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00001740
Chris Lattner6656dd12006-01-31 02:03:41 +00001741 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1742
1743 // Process indirect outputs, first output all of the flagged copies out of
1744 // physregs.
1745 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00001746 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00001747 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00001748 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1749 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00001750 }
1751
1752 // Emit the non-flagged stores from the physregs.
1753 std::vector<SDOperand> OutChains;
1754 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1755 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1756 StoresToEmit[i].first,
1757 getValue(StoresToEmit[i].second),
1758 DAG.getSrcValue(StoresToEmit[i].second)));
1759 if (!OutChains.empty())
1760 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattnerce7518c2006-01-26 22:24:51 +00001761 DAG.setRoot(Chain);
1762}
1763
1764
Chris Lattner1c08c712005-01-07 07:47:53 +00001765void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1766 SDOperand Src = getValue(I.getOperand(0));
1767
1768 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00001769
1770 if (IntPtr < Src.getValueType())
1771 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1772 else if (IntPtr > Src.getValueType())
1773 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00001774
1775 // Scale the source by the type size.
1776 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1777 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1778 Src, getIntPtrConstant(ElementSize));
1779
1780 std::vector<std::pair<SDOperand, const Type*> > Args;
1781 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00001782
1783 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001784 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001785 DAG.getExternalSymbol("malloc", IntPtr),
1786 Args, DAG);
1787 setValue(&I, Result.first); // Pointers always fit in registers
1788 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001789}
1790
1791void SelectionDAGLowering::visitFree(FreeInst &I) {
1792 std::vector<std::pair<SDOperand, const Type*> > Args;
1793 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1794 TLI.getTargetData().getIntPtrType()));
1795 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00001796 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001797 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001798 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1799 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001800}
1801
Chris Lattner025c39b2005-08-26 20:54:47 +00001802// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1803// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1804// instructions are special in various ways, which require special support to
1805// insert. The specified MachineInstr is created but not inserted into any
1806// basic blocks, and the scheduler passes ownership of it to this method.
1807MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1808 MachineBasicBlock *MBB) {
1809 std::cerr << "If a target marks an instruction with "
1810 "'usesCustomDAGSchedInserter', it must implement "
1811 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1812 abort();
1813 return 0;
1814}
1815
Chris Lattner39ae3622005-01-09 00:00:49 +00001816void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001817 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1818 getValue(I.getOperand(1)),
1819 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00001820}
1821
1822void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001823 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1824 getValue(I.getOperand(0)),
1825 DAG.getSrcValue(I.getOperand(0)));
1826 setValue(&I, V);
1827 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00001828}
1829
1830void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001831 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1832 getValue(I.getOperand(1)),
1833 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001834}
1835
1836void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001837 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1838 getValue(I.getOperand(1)),
1839 getValue(I.getOperand(2)),
1840 DAG.getSrcValue(I.getOperand(1)),
1841 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001842}
1843
Chris Lattner39ae3622005-01-09 00:00:49 +00001844// It is always conservatively correct for llvm.returnaddress and
1845// llvm.frameaddress to return 0.
1846std::pair<SDOperand, SDOperand>
1847TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1848 unsigned Depth, SelectionDAG &DAG) {
1849 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00001850}
1851
Chris Lattner50381b62005-05-14 05:50:48 +00001852SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00001853 assert(0 && "LowerOperation not implemented for this target!");
1854 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001855 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00001856}
1857
Nate Begeman0aed7842006-01-28 03:14:31 +00001858SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1859 SelectionDAG &DAG) {
1860 assert(0 && "CustomPromoteOperation not implemented for this target!");
1861 abort();
1862 return SDOperand();
1863}
1864
Chris Lattner39ae3622005-01-09 00:00:49 +00001865void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1866 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1867 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00001868 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001869 setValue(&I, Result.first);
1870 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001871}
1872
Evan Cheng74d0aa92006-02-15 21:59:04 +00001873/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00001874/// operand.
1875static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00001876 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001877 MVT::ValueType CurVT = VT;
1878 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1879 uint64_t Val = C->getValue() & 255;
1880 unsigned Shift = 8;
1881 while (CurVT != MVT::i8) {
1882 Val = (Val << Shift) | Val;
1883 Shift <<= 1;
1884 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001885 }
1886 return DAG.getConstant(Val, VT);
1887 } else {
1888 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1889 unsigned Shift = 8;
1890 while (CurVT != MVT::i8) {
1891 Value =
1892 DAG.getNode(ISD::OR, VT,
1893 DAG.getNode(ISD::SHL, VT, Value,
1894 DAG.getConstant(Shift, MVT::i8)), Value);
1895 Shift <<= 1;
1896 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001897 }
1898
1899 return Value;
1900 }
1901}
1902
Evan Cheng74d0aa92006-02-15 21:59:04 +00001903/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1904/// used when a memcpy is turned into a memset when the source is a constant
1905/// string ptr.
1906static SDOperand getMemsetStringVal(MVT::ValueType VT,
1907 SelectionDAG &DAG, TargetLowering &TLI,
1908 std::string &Str, unsigned Offset) {
1909 MVT::ValueType CurVT = VT;
1910 uint64_t Val = 0;
1911 unsigned MSB = getSizeInBits(VT) / 8;
1912 if (TLI.isLittleEndian())
1913 Offset = Offset + MSB - 1;
1914 for (unsigned i = 0; i != MSB; ++i) {
1915 Val = (Val << 8) | Str[Offset];
1916 Offset += TLI.isLittleEndian() ? -1 : 1;
1917 }
1918 return DAG.getConstant(Val, VT);
1919}
1920
Evan Cheng1db92f92006-02-14 08:22:34 +00001921/// getMemBasePlusOffset - Returns base and offset node for the
1922static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1923 SelectionDAG &DAG, TargetLowering &TLI) {
1924 MVT::ValueType VT = Base.getValueType();
1925 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1926}
1927
Evan Chengc4f8eee2006-02-14 20:12:38 +00001928/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00001929/// to replace the memset / memcpy is below the threshold. It also returns the
1930/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00001931static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1932 unsigned Limit, uint64_t Size,
1933 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001934 MVT::ValueType VT;
1935
1936 if (TLI.allowsUnalignedMemoryAccesses()) {
1937 VT = MVT::i64;
1938 } else {
1939 switch (Align & 7) {
1940 case 0:
1941 VT = MVT::i64;
1942 break;
1943 case 4:
1944 VT = MVT::i32;
1945 break;
1946 case 2:
1947 VT = MVT::i16;
1948 break;
1949 default:
1950 VT = MVT::i8;
1951 break;
1952 }
1953 }
1954
Evan Cheng80e89d72006-02-14 09:11:59 +00001955 MVT::ValueType LVT = MVT::i64;
1956 while (!TLI.isTypeLegal(LVT))
1957 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1958 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00001959
Evan Cheng80e89d72006-02-14 09:11:59 +00001960 if (VT > LVT)
1961 VT = LVT;
1962
Evan Chengdea72452006-02-14 23:05:54 +00001963 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00001964 while (Size != 0) {
1965 unsigned VTSize = getSizeInBits(VT) / 8;
1966 while (VTSize > Size) {
1967 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001968 VTSize >>= 1;
1969 }
Evan Cheng80e89d72006-02-14 09:11:59 +00001970 assert(MVT::isInteger(VT));
1971
1972 if (++NumMemOps > Limit)
1973 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00001974 MemOps.push_back(VT);
1975 Size -= VTSize;
1976 }
Evan Cheng80e89d72006-02-14 09:11:59 +00001977
1978 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00001979}
1980
Chris Lattner7041ee32005-01-11 05:56:49 +00001981void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001982 SDOperand Op1 = getValue(I.getOperand(1));
1983 SDOperand Op2 = getValue(I.getOperand(2));
1984 SDOperand Op3 = getValue(I.getOperand(3));
1985 SDOperand Op4 = getValue(I.getOperand(4));
1986 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1987 if (Align == 0) Align = 1;
1988
1989 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1990 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00001991
1992 // Expand memset / memcpy to a series of load / store ops
1993 // if the size operand falls below a certain threshold.
1994 std::vector<SDOperand> OutChains;
1995 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00001996 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00001997 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00001998 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1999 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00002000 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00002001 unsigned Offset = 0;
2002 for (unsigned i = 0; i < NumMemOps; i++) {
2003 MVT::ValueType VT = MemOps[i];
2004 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00002005 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengc080d6f2006-02-15 01:54:51 +00002006 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2007 Value,
Chris Lattner864635a2006-02-22 22:37:12 +00002008 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2009 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chengc080d6f2006-02-15 01:54:51 +00002010 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00002011 Offset += VTSize;
2012 }
Evan Cheng1db92f92006-02-14 08:22:34 +00002013 }
Evan Chengc080d6f2006-02-15 01:54:51 +00002014 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00002015 }
Evan Chengc080d6f2006-02-15 01:54:51 +00002016 case ISD::MEMCPY: {
2017 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2018 Size->getValue(), Align, TLI)) {
2019 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00002020 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00002021 GlobalAddressSDNode *G = NULL;
2022 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00002023 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00002024
2025 if (Op2.getOpcode() == ISD::GlobalAddress)
2026 G = cast<GlobalAddressSDNode>(Op2);
2027 else if (Op2.getOpcode() == ISD::ADD &&
2028 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2029 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2030 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00002031 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00002032 }
2033 if (G) {
2034 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengcffbb512006-02-16 23:11:42 +00002035 if (GV) {
Evan Cheng09371032006-03-10 23:52:03 +00002036 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00002037 if (!Str.empty()) {
2038 CopyFromStr = true;
2039 SrcOff += SrcDelta;
2040 }
2041 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00002042 }
2043
Evan Chengc080d6f2006-02-15 01:54:51 +00002044 for (unsigned i = 0; i < NumMemOps; i++) {
2045 MVT::ValueType VT = MemOps[i];
2046 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00002047 SDOperand Value, Chain, Store;
2048
Evan Chengcffbb512006-02-16 23:11:42 +00002049 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00002050 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2051 Chain = getRoot();
2052 Store =
2053 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2054 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2055 DAG.getSrcValue(I.getOperand(1), DstOff));
2056 } else {
2057 Value = DAG.getLoad(VT, getRoot(),
2058 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2059 DAG.getSrcValue(I.getOperand(2), SrcOff));
2060 Chain = Value.getValue(1);
2061 Store =
2062 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2063 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2064 DAG.getSrcValue(I.getOperand(1), DstOff));
2065 }
Evan Chengc080d6f2006-02-15 01:54:51 +00002066 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00002067 SrcOff += VTSize;
2068 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00002069 }
2070 }
2071 break;
2072 }
2073 }
2074
2075 if (!OutChains.empty()) {
2076 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2077 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00002078 }
2079 }
2080
Chris Lattner7041ee32005-01-11 05:56:49 +00002081 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +00002082 Ops.push_back(getRoot());
Evan Cheng1db92f92006-02-14 08:22:34 +00002083 Ops.push_back(Op1);
2084 Ops.push_back(Op2);
2085 Ops.push_back(Op3);
2086 Ops.push_back(Op4);
Chris Lattner7041ee32005-01-11 05:56:49 +00002087 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +00002088}
2089
Chris Lattner7041ee32005-01-11 05:56:49 +00002090//===----------------------------------------------------------------------===//
2091// SelectionDAGISel code
2092//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00002093
2094unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2095 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2096}
2097
Chris Lattner495a0b52005-08-17 06:37:43 +00002098void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00002099 // FIXME: we only modify the CFG to split critical edges. This
2100 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +00002101}
Chris Lattner1c08c712005-01-07 07:47:53 +00002102
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002103
2104/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2105/// casting to the type of GEPI.
2106static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2107 Value *Ptr, Value *PtrOffset) {
2108 if (V) return V; // Already computed.
2109
2110 BasicBlock::iterator InsertPt;
2111 if (BB == GEPI->getParent()) {
2112 // If insert into the GEP's block, insert right after the GEP.
2113 InsertPt = GEPI;
2114 ++InsertPt;
2115 } else {
2116 // Otherwise, insert at the top of BB, after any PHI nodes
2117 InsertPt = BB->begin();
2118 while (isa<PHINode>(InsertPt)) ++InsertPt;
2119 }
2120
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002121 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2122 // BB so that there is only one value live across basic blocks (the cast
2123 // operand).
2124 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2125 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2126 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2127
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002128 // Add the offset, cast it to the right type.
2129 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2130 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2131 return V = Ptr;
2132}
2133
2134
2135/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2136/// selection, we want to be a bit careful about some things. In particular, if
2137/// we have a GEP instruction that is used in a different block than it is
2138/// defined, the addressing expression of the GEP cannot be folded into loads or
2139/// stores that use it. In this case, decompose the GEP and move constant
2140/// indices into blocks that use it.
2141static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2142 const TargetData &TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002143 // If this GEP is only used inside the block it is defined in, there is no
2144 // need to rewrite it.
2145 bool isUsedOutsideDefBB = false;
2146 BasicBlock *DefBB = GEPI->getParent();
2147 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2148 UI != E; ++UI) {
2149 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2150 isUsedOutsideDefBB = true;
2151 break;
2152 }
2153 }
2154 if (!isUsedOutsideDefBB) return;
2155
2156 // If this GEP has no non-zero constant indices, there is nothing we can do,
2157 // ignore it.
2158 bool hasConstantIndex = false;
2159 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2160 E = GEPI->op_end(); OI != E; ++OI) {
2161 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2162 if (CI->getRawValue()) {
2163 hasConstantIndex = true;
2164 break;
2165 }
2166 }
Chris Lattner3802c252005-12-11 09:05:13 +00002167 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2168 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002169
2170 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2171 // constant offset (which we now know is non-zero) and deal with it later.
2172 uint64_t ConstantOffset = 0;
2173 const Type *UIntPtrTy = TD.getIntPtrType();
2174 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2175 const Type *Ty = GEPI->getOperand(0)->getType();
2176
2177 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2178 E = GEPI->op_end(); OI != E; ++OI) {
2179 Value *Idx = *OI;
2180 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2181 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2182 if (Field)
2183 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2184 Ty = StTy->getElementType(Field);
2185 } else {
2186 Ty = cast<SequentialType>(Ty)->getElementType();
2187
2188 // Handle constant subscripts.
2189 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2190 if (CI->getRawValue() == 0) continue;
2191
2192 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2193 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2194 else
2195 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2196 continue;
2197 }
2198
2199 // Ptr = Ptr + Idx * ElementSize;
2200
2201 // Cast Idx to UIntPtrTy if needed.
2202 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2203
2204 uint64_t ElementSize = TD.getTypeSize(Ty);
2205 // Mask off bits that should not be set.
2206 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2207 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2208
2209 // Multiply by the element size and add to the base.
2210 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2211 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2212 }
2213 }
2214
2215 // Make sure that the offset fits in uintptr_t.
2216 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2217 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2218
2219 // Okay, we have now emitted all of the variable index parts to the BB that
2220 // the GEP is defined in. Loop over all of the using instructions, inserting
2221 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002222 // instruction to use the newly computed value, making GEPI dead. When the
2223 // user is a load or store instruction address, we emit the add into the user
2224 // block, otherwise we use a canonical version right next to the gep (these
2225 // won't be foldable as addresses, so we might as well share the computation).
2226
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002227 std::map<BasicBlock*,Value*> InsertedExprs;
2228 while (!GEPI->use_empty()) {
2229 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002230
2231 // If this use is not foldable into the addressing mode, use a version
2232 // emitted in the GEP block.
2233 Value *NewVal;
2234 if (!isa<LoadInst>(User) &&
2235 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2236 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2237 Ptr, PtrOffset);
2238 } else {
2239 // Otherwise, insert the code in the User's block so it can be folded into
2240 // any users in that block.
2241 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002242 User->getParent(), GEPI,
2243 Ptr, PtrOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002244 }
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002245 User->replaceUsesOfWith(GEPI, NewVal);
2246 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002247
2248 // Finally, the GEP is dead, remove it.
2249 GEPI->eraseFromParent();
2250}
2251
Chris Lattner1c08c712005-01-07 07:47:53 +00002252bool SelectionDAGISel::runOnFunction(Function &Fn) {
2253 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2254 RegMap = MF.getSSARegMap();
2255 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2256
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002257 // First, split all critical edges for PHI nodes with incoming values that are
2258 // constants, this way the load of the constant into a vreg will not be placed
2259 // into MBBs that are used some other way.
2260 //
2261 // In this pass we also look for GEP instructions that are used across basic
2262 // blocks and rewrites them to improve basic-block-at-a-time selection.
2263 //
Chris Lattner36b708f2005-08-18 17:35:14 +00002264 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2265 PHINode *PN;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002266 BasicBlock::iterator BBI;
2267 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner36b708f2005-08-18 17:35:14 +00002268 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2269 if (isa<Constant>(PN->getIncomingValue(i)))
2270 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002271
2272 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2273 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2274 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner36b708f2005-08-18 17:35:14 +00002275 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002276
Chris Lattner1c08c712005-01-07 07:47:53 +00002277 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2278
2279 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2280 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00002281
Chris Lattner1c08c712005-01-07 07:47:53 +00002282 return true;
2283}
2284
2285
Chris Lattnerddb870b2005-01-13 17:59:43 +00002286SDOperand SelectionDAGISel::
2287CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002288 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00002289 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002290 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00002291 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002292
2293 // If this type is not legal, we must make sure to not create an invalid
2294 // register use.
2295 MVT::ValueType SrcVT = Op.getValueType();
2296 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2297 SelectionDAG &DAG = SDL.DAG;
2298 if (SrcVT == DestVT) {
2299 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2300 } else if (SrcVT < DestVT) {
2301 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00002302 if (MVT::isFloatingPoint(SrcVT))
2303 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2304 else
Chris Lattnerfab08872005-09-02 00:19:37 +00002305 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002306 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2307 } else {
2308 // The src value is expanded into multiple registers.
2309 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2310 Op, DAG.getConstant(0, MVT::i32));
2311 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2312 Op, DAG.getConstant(1, MVT::i32));
2313 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2314 return DAG.getCopyToReg(Op, Reg+1, Hi);
2315 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002316}
2317
Chris Lattner068a81e2005-01-17 17:15:02 +00002318void SelectionDAGISel::
2319LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2320 std::vector<SDOperand> &UnorderedChains) {
2321 // If this is the entry block, emit arguments.
2322 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00002323 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00002324 SDOperand OldRoot = SDL.DAG.getRoot();
2325 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00002326
Chris Lattnerbf209482005-10-30 19:42:35 +00002327 unsigned a = 0;
2328 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2329 AI != E; ++AI, ++a)
2330 if (!AI->use_empty()) {
2331 SDL.setValue(AI, Args[a]);
Chris Lattnerfa577022005-09-13 19:30:54 +00002332
Chris Lattnerbf209482005-10-30 19:42:35 +00002333 // If this argument is live outside of the entry block, insert a copy from
2334 // whereever we got it to the vreg that other BB's will reference it as.
2335 if (FuncInfo.ValueMap.count(AI)) {
2336 SDOperand Copy =
2337 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2338 UnorderedChains.push_back(Copy);
2339 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00002340 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002341
2342 // Next, if the function has live ins that need to be copied into vregs,
2343 // emit the copies now, into the top of the block.
2344 MachineFunction &MF = SDL.DAG.getMachineFunction();
2345 if (MF.livein_begin() != MF.livein_end()) {
2346 SSARegMap *RegMap = MF.getSSARegMap();
2347 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2348 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2349 E = MF.livein_end(); LI != E; ++LI)
2350 if (LI->second)
2351 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2352 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner068a81e2005-01-17 17:15:02 +00002353 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002354
2355 // Finally, if the target has anything special to do, allow it to do so.
2356 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00002357}
2358
2359
Chris Lattner1c08c712005-01-07 07:47:53 +00002360void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2361 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2362 FunctionLoweringInfo &FuncInfo) {
2363 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002364
2365 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002366
Chris Lattnerbf209482005-10-30 19:42:35 +00002367 // Lower any arguments needed in this block if this is the entry block.
2368 if (LLVMBB == &LLVMBB->getParent()->front())
2369 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00002370
2371 BB = FuncInfo.MBBMap[LLVMBB];
2372 SDL.setCurrentBasicBlock(BB);
2373
2374 // Lower all of the non-terminator instructions.
2375 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2376 I != E; ++I)
2377 SDL.visit(*I);
2378
2379 // Ensure that all instructions which are used outside of their defining
2380 // blocks are available as virtual registers.
2381 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002382 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00002383 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00002384 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00002385 UnorderedChains.push_back(
2386 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00002387 }
2388
2389 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2390 // ensure constants are generated when needed. Remember the virtual registers
2391 // that need to be added to the Machine PHI nodes as input. We cannot just
2392 // directly add them, because expansion might result in multiple MBB's for one
2393 // BB. As such, the start of the BB might correspond to a different MBB than
2394 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00002395 //
Chris Lattner1c08c712005-01-07 07:47:53 +00002396
2397 // Emit constants only once even if used by multiple PHI nodes.
2398 std::map<Constant*, unsigned> ConstantsOut;
2399
2400 // Check successor nodes PHI nodes that expect a constant to be available from
2401 // this block.
2402 TerminatorInst *TI = LLVMBB->getTerminator();
2403 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2404 BasicBlock *SuccBB = TI->getSuccessor(succ);
2405 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2406 PHINode *PN;
2407
2408 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2409 // nodes and Machine PHI nodes, but the incoming operands have not been
2410 // emitted yet.
2411 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00002412 (PN = dyn_cast<PHINode>(I)); ++I)
2413 if (!PN->use_empty()) {
2414 unsigned Reg;
2415 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2416 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2417 unsigned &RegOut = ConstantsOut[C];
2418 if (RegOut == 0) {
2419 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002420 UnorderedChains.push_back(
2421 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00002422 }
2423 Reg = RegOut;
2424 } else {
2425 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00002426 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00002427 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00002428 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2429 "Didn't codegen value into a register!??");
2430 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002431 UnorderedChains.push_back(
2432 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00002433 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002434 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002435
Chris Lattnerf44fd882005-01-07 21:34:19 +00002436 // Remember that this register needs to added to the machine PHI node as
2437 // the input for this MBB.
2438 unsigned NumElements =
2439 TLI.getNumElements(TLI.getValueType(PN->getType()));
2440 for (unsigned i = 0, e = NumElements; i != e; ++i)
2441 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00002442 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002443 }
2444 ConstantsOut.clear();
2445
Chris Lattnerddb870b2005-01-13 17:59:43 +00002446 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00002447 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00002448 SDOperand Root = SDL.getRoot();
2449 if (Root.getOpcode() != ISD::EntryToken) {
2450 unsigned i = 0, e = UnorderedChains.size();
2451 for (; i != e; ++i) {
2452 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2453 if (UnorderedChains[i].Val->getOperand(0) == Root)
2454 break; // Don't add the root if we already indirectly depend on it.
2455 }
2456
2457 if (i == e)
2458 UnorderedChains.push_back(Root);
2459 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00002460 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2461 }
2462
Chris Lattner1c08c712005-01-07 07:47:53 +00002463 // Lower the terminator after the copies are emitted.
2464 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00002465
2466 // Make sure the root of the DAG is up-to-date.
2467 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00002468}
2469
2470void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2471 FunctionLoweringInfo &FuncInfo) {
Jim Laskeyb2efb852006-01-04 22:28:25 +00002472 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner1c08c712005-01-07 07:47:53 +00002473 CurDAG = &DAG;
2474 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2475
2476 // First step, lower LLVM code to some DAG. This DAG may use operations and
2477 // types that are not supported by the target.
2478 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2479
Chris Lattneraf21d552005-10-10 16:47:10 +00002480 // Run the DAG combiner in pre-legalize mode.
2481 DAG.Combine(false);
Nate Begeman2300f552005-09-07 00:15:36 +00002482
Chris Lattner1c08c712005-01-07 07:47:53 +00002483 DEBUG(std::cerr << "Lowered selection DAG:\n");
2484 DEBUG(DAG.dump());
2485
2486 // Second step, hack on the DAG until it only uses operations and types that
2487 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00002488 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00002489
2490 DEBUG(std::cerr << "Legalized selection DAG:\n");
2491 DEBUG(DAG.dump());
2492
Chris Lattneraf21d552005-10-10 16:47:10 +00002493 // Run the DAG combiner in post-legalize mode.
2494 DAG.Combine(true);
Nate Begeman2300f552005-09-07 00:15:36 +00002495
Evan Chenga9c20912006-01-21 02:32:06 +00002496 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattnerd48050a2005-10-05 06:09:10 +00002497
Chris Lattnera33ef482005-03-30 01:10:47 +00002498 // Third, instruction select all of the operations to machine code, adding the
2499 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00002500 InstructionSelectBasicBlock(DAG);
2501
Chris Lattner1c08c712005-01-07 07:47:53 +00002502 DEBUG(std::cerr << "Selected machine code:\n");
2503 DEBUG(BB->dump());
2504
Chris Lattnera33ef482005-03-30 01:10:47 +00002505 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00002506 // PHI nodes in successors.
2507 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2508 MachineInstr *PHI = PHINodesToUpdate[i].first;
2509 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2510 "This is not a machine PHI node that we are updating!");
2511 PHI->addRegOperand(PHINodesToUpdate[i].second);
2512 PHI->addMachineBasicBlockOperand(BB);
2513 }
Chris Lattnera33ef482005-03-30 01:10:47 +00002514
2515 // Finally, add the CFG edges from the last selected MBB to the successor
2516 // MBBs.
2517 TerminatorInst *TI = LLVMBB->getTerminator();
2518 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2519 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2520 BB->addSuccessor(Succ0MBB);
2521 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002522}
Evan Chenga9c20912006-01-21 02:32:06 +00002523
2524//===----------------------------------------------------------------------===//
2525/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2526/// target node in the graph.
2527void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2528 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00002529 ScheduleDAG *SL = NULL;
2530
2531 switch (ISHeuristic) {
2532 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Cheng3f239522006-01-25 09:12:57 +00002533 case defaultScheduling:
2534 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2535 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2536 else /* TargetLowering::SchedulingForRegPressure */
2537 SL = createBURRListDAGScheduler(DAG, BB);
2538 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002539 case noScheduling:
Chris Lattner20a49212006-03-10 07:49:12 +00002540 SL = createBFS_DAGScheduler(DAG, BB);
2541 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002542 case simpleScheduling:
Chris Lattner20a49212006-03-10 07:49:12 +00002543 SL = createSimpleDAGScheduler(false, DAG, BB);
2544 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002545 case simpleNoItinScheduling:
Chris Lattner20a49212006-03-10 07:49:12 +00002546 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Cheng4ef10862006-01-23 07:01:07 +00002547 break;
Evan Chengf0f9c902006-01-23 08:26:10 +00002548 case listSchedulingBURR:
2549 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattnera5de4842006-03-05 21:10:33 +00002550 break;
Chris Lattner03fc53c2006-03-06 00:22:00 +00002551 case listSchedulingTD:
Chris Lattnerb0d21ef2006-03-08 04:25:59 +00002552 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattnera5de4842006-03-05 21:10:33 +00002553 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002554 }
Chris Lattnera3818e62006-01-21 19:12:11 +00002555 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00002556 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00002557}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00002558
Chris Lattnerb0d21ef2006-03-08 04:25:59 +00002559HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2560 return new HazardRecognizer();
Chris Lattner03fc53c2006-03-06 00:22:00 +00002561}
2562
Chris Lattner0e43f2b2006-02-24 02:13:54 +00002563/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2564/// by tblgen. Others should not call it.
2565void SelectionDAGISel::
2566SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2567 std::vector<SDOperand> InOps;
2568 std::swap(InOps, Ops);
2569
2570 Ops.push_back(InOps[0]); // input chain.
2571 Ops.push_back(InOps[1]); // input asm string.
2572
2573 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2574 unsigned i = 2, e = InOps.size();
2575 if (InOps[e-1].getValueType() == MVT::Flag)
2576 --e; // Don't process a flag operand if it is here.
2577
2578 while (i != e) {
2579 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2580 if ((Flags & 7) != 4 /*MEM*/) {
2581 // Just skip over this operand, copying the operands verbatim.
2582 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2583 i += (Flags >> 3) + 1;
2584 } else {
2585 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2586 // Otherwise, this is a memory operand. Ask the target to select it.
2587 std::vector<SDOperand> SelOps;
2588 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2589 std::cerr << "Could not match memory address. Inline asm failure!\n";
2590 exit(1);
2591 }
2592
2593 // Add this to the output node.
2594 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2595 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2596 i += 2;
2597 }
2598 }
2599
2600 // Add the flag input back if present.
2601 if (e != InOps.size())
2602 Ops.push_back(InOps.back());
2603}