blob: 3e97494a26e77b522c17659c2f2ff6806173d305 [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
Evan Cheng4ef10862006-01-23 07:01:07 +000060namespace {
61 cl::opt<SchedHeuristics>
62 ISHeuristic(
63 "sched",
64 cl::desc("Choose scheduling style"),
Evan Cheng3f239522006-01-25 09:12:57 +000065 cl::init(defaultScheduling),
Evan Cheng4ef10862006-01-23 07:01:07 +000066 cl::values(
Evan Cheng3f239522006-01-25 09:12:57 +000067 clEnumValN(defaultScheduling, "default",
68 "Target preferred scheduling style"),
Evan Cheng4ef10862006-01-23 07:01:07 +000069 clEnumValN(noScheduling, "none",
Jim Laskey17d52f72006-01-23 13:34:04 +000070 "No scheduling: breadth first sequencing"),
Evan Cheng4ef10862006-01-23 07:01:07 +000071 clEnumValN(simpleScheduling, "simple",
72 "Simple two pass scheduling: minimize critical path "
73 "and maximize processor utilization"),
74 clEnumValN(simpleNoItinScheduling, "simple-noitin",
75 "Simple two pass scheduling: Same as simple "
76 "except using generic latency"),
Evan Cheng3f239522006-01-25 09:12:57 +000077 clEnumValN(listSchedulingBURR, "list-burr",
Evan Chengf0f9c902006-01-23 08:26:10 +000078 "Bottom up register reduction list scheduling"),
Chris Lattner03fc53c2006-03-06 00:22:00 +000079 clEnumValN(listSchedulingTD, "list-td",
80 "Top-down list scheduler"),
Evan Cheng4ef10862006-01-23 07:01:07 +000081 clEnumValEnd));
82} // namespace
83
Chris Lattner864635a2006-02-22 22:37:12 +000084namespace {
85 /// RegsForValue - This struct represents the physical registers that a
86 /// particular value is assigned and the type information about the value.
87 /// This is needed because values can be promoted into larger registers and
88 /// expanded into multiple smaller registers than the value.
89 struct RegsForValue {
90 /// Regs - This list hold the register (for legal and promoted values)
91 /// or register set (for expanded values) that the value should be assigned
92 /// to.
93 std::vector<unsigned> Regs;
94
95 /// RegVT - The value type of each register.
96 ///
97 MVT::ValueType RegVT;
98
99 /// ValueVT - The value type of the LLVM value, which may be promoted from
100 /// RegVT or made from merging the two expanded parts.
101 MVT::ValueType ValueVT;
102
103 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
104
105 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
106 : RegVT(regvt), ValueVT(valuevt) {
107 Regs.push_back(Reg);
108 }
109 RegsForValue(const std::vector<unsigned> &regs,
110 MVT::ValueType regvt, MVT::ValueType valuevt)
111 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
112 }
113
114 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
115 /// this value and returns the result as a ValueVT value. This uses
116 /// Chain/Flag as the input and updates them for the output Chain/Flag.
117 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000118 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000119
120 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
121 /// specified value into the registers specified by this object. This uses
122 /// Chain/Flag as the input and updates them for the output Chain/Flag.
123 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000124 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000125
126 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
127 /// operand list. This adds the code marker and includes the number of
128 /// values added into it.
129 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000130 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000131 };
132}
Evan Cheng4ef10862006-01-23 07:01:07 +0000133
Chris Lattner1c08c712005-01-07 07:47:53 +0000134namespace llvm {
135 //===--------------------------------------------------------------------===//
136 /// FunctionLoweringInfo - This contains information that is global to a
137 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000138 class FunctionLoweringInfo {
139 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000140 TargetLowering &TLI;
141 Function &Fn;
142 MachineFunction &MF;
143 SSARegMap *RegMap;
144
145 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
146
147 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
148 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
149
150 /// ValueMap - Since we emit code for the function a basic block at a time,
151 /// we must remember which virtual registers hold the values for
152 /// cross-basic-block values.
153 std::map<const Value*, unsigned> ValueMap;
154
155 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
156 /// the entry block. This allows the allocas to be efficiently referenced
157 /// anywhere in the function.
158 std::map<const AllocaInst*, int> StaticAllocaMap;
159
160 unsigned MakeReg(MVT::ValueType VT) {
161 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
162 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000163
Chris Lattner1c08c712005-01-07 07:47:53 +0000164 unsigned CreateRegForValue(const Value *V) {
165 MVT::ValueType VT = TLI.getValueType(V->getType());
166 // The common case is that we will only create one register for this
167 // value. If we have that case, create and return the virtual register.
168 unsigned NV = TLI.getNumElements(VT);
Chris Lattnerfb849802005-01-16 00:37:38 +0000169 if (NV == 1) {
170 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +0000171 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +0000172 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000173
Chris Lattner1c08c712005-01-07 07:47:53 +0000174 // If this value is represented with multiple target registers, make sure
Chris Lattner864635a2006-02-22 22:37:12 +0000175 // to create enough consecutive registers of the right (smaller) type.
Chris Lattner1c08c712005-01-07 07:47:53 +0000176 unsigned NT = VT-1; // Find the type to use.
177 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
178 --NT;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000179
Chris Lattner1c08c712005-01-07 07:47:53 +0000180 unsigned R = MakeReg((MVT::ValueType)NT);
181 for (unsigned i = 1; i != NV; ++i)
182 MakeReg((MVT::ValueType)NT);
183 return R;
184 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000185
Chris Lattner1c08c712005-01-07 07:47:53 +0000186 unsigned InitializeRegForValue(const Value *V) {
187 unsigned &R = ValueMap[V];
188 assert(R == 0 && "Already initialized this value register!");
189 return R = CreateRegForValue(V);
190 }
191 };
192}
193
194/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
195/// PHI nodes or outside of the basic block that defines it.
196static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
197 if (isa<PHINode>(I)) return true;
198 BasicBlock *BB = I->getParent();
199 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
200 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
201 return true;
202 return false;
203}
204
Chris Lattnerbf209482005-10-30 19:42:35 +0000205/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
206/// entry block, return true.
207static bool isOnlyUsedInEntryBlock(Argument *A) {
208 BasicBlock *Entry = A->getParent()->begin();
209 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
210 if (cast<Instruction>(*UI)->getParent() != Entry)
211 return false; // Use not in entry block.
212 return true;
213}
214
Chris Lattner1c08c712005-01-07 07:47:53 +0000215FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000216 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000217 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
218
Chris Lattnerbf209482005-10-30 19:42:35 +0000219 // Create a vreg for each argument register that is not dead and is used
220 // outside of the entry block for the function.
221 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
222 AI != E; ++AI)
223 if (!isOnlyUsedInEntryBlock(AI))
224 InitializeRegForValue(AI);
225
Chris Lattner1c08c712005-01-07 07:47:53 +0000226 // Initialize the mapping of values to registers. This is only set up for
227 // instruction values that are used outside of the block that defines
228 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000229 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000230 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
231 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
232 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
233 const Type *Ty = AI->getAllocatedType();
234 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000235 unsigned Align =
236 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
237 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000238
239 // If the alignment of the value is smaller than the size of the value,
240 // and if the size of the value is particularly small (<= 8 bytes),
241 // round up to the size of the value for potentially better performance.
242 //
243 // FIXME: This could be made better with a preferred alignment hook in
244 // TargetData. It serves primarily to 8-byte align doubles for X86.
245 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner2dfa8192005-10-18 22:11:42 +0000246 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000247 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000248 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000249 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000250 }
251
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000252 for (; BB != EB; ++BB)
253 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000254 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
255 if (!isa<AllocaInst>(I) ||
256 !StaticAllocaMap.count(cast<AllocaInst>(I)))
257 InitializeRegForValue(I);
258
259 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
260 // also creates the initial PHI MachineInstrs, though none of the input
261 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000262 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000263 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
264 MBBMap[BB] = MBB;
265 MF.getBasicBlockList().push_back(MBB);
266
267 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
268 // appropriate.
269 PHINode *PN;
270 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000271 (PN = dyn_cast<PHINode>(I)); ++I)
272 if (!PN->use_empty()) {
273 unsigned NumElements =
274 TLI.getNumElements(TLI.getValueType(PN->getType()));
275 unsigned PHIReg = ValueMap[PN];
276 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
277 for (unsigned i = 0; i != NumElements; ++i)
278 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
279 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000280 }
281}
282
283
284
285//===----------------------------------------------------------------------===//
286/// SelectionDAGLowering - This is the common target-independent lowering
287/// implementation that is parameterized by a TargetLowering object.
288/// Also, targets can overload any lowering method.
289///
290namespace llvm {
291class SelectionDAGLowering {
292 MachineBasicBlock *CurMBB;
293
294 std::map<const Value*, SDOperand> NodeMap;
295
Chris Lattnerd3948112005-01-17 22:19:26 +0000296 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
297 /// them up and then emit token factor nodes when possible. This allows us to
298 /// get simple disambiguation between loads without worrying about alias
299 /// analysis.
300 std::vector<SDOperand> PendingLoads;
301
Chris Lattner1c08c712005-01-07 07:47:53 +0000302public:
303 // TLI - This is information that describes the available target features we
304 // need for lowering. This indicates when operations are unavailable,
305 // implemented with a libcall, etc.
306 TargetLowering &TLI;
307 SelectionDAG &DAG;
308 const TargetData &TD;
309
310 /// FuncInfo - Information about the function as a whole.
311 ///
312 FunctionLoweringInfo &FuncInfo;
313
314 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000315 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000316 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
317 FuncInfo(funcinfo) {
318 }
319
Chris Lattnera651cf62005-01-17 19:43:36 +0000320 /// getRoot - Return the current virtual root of the Selection DAG.
321 ///
322 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000323 if (PendingLoads.empty())
324 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000325
Chris Lattnerd3948112005-01-17 22:19:26 +0000326 if (PendingLoads.size() == 1) {
327 SDOperand Root = PendingLoads[0];
328 DAG.setRoot(Root);
329 PendingLoads.clear();
330 return Root;
331 }
332
333 // Otherwise, we have to make a token factor node.
334 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
335 PendingLoads.clear();
336 DAG.setRoot(Root);
337 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000338 }
339
Chris Lattner1c08c712005-01-07 07:47:53 +0000340 void visit(Instruction &I) { visit(I.getOpcode(), I); }
341
342 void visit(unsigned Opcode, User &I) {
343 switch (Opcode) {
344 default: assert(0 && "Unknown instruction type encountered!");
345 abort();
346 // Build the switch statement using the Instruction.def file.
347#define HANDLE_INST(NUM, OPCODE, CLASS) \
348 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
349#include "llvm/Instruction.def"
350 }
351 }
352
353 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
354
355
356 SDOperand getIntPtrConstant(uint64_t Val) {
357 return DAG.getConstant(Val, TLI.getPointerTy());
358 }
359
360 SDOperand getValue(const Value *V) {
361 SDOperand &N = NodeMap[V];
362 if (N.Val) return N;
363
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000364 const Type *VTy = V->getType();
365 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner1c08c712005-01-07 07:47:53 +0000366 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
367 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
368 visit(CE->getOpcode(), *CE);
369 assert(N.Val && "visit didn't populate the ValueMap!");
370 return N;
371 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
372 return N = DAG.getGlobalAddress(GV, VT);
373 } else if (isa<ConstantPointerNull>(C)) {
374 return N = DAG.getConstant(0, TLI.getPointerTy());
375 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000376 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000377 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
378 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000379 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
380 unsigned NumElements = PTy->getNumElements();
381 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
382 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
383
384 // Now that we know the number and type of the elements, push a
385 // Constant or ConstantFP node onto the ops list for each element of
386 // the packed constant.
387 std::vector<SDOperand> Ops;
Chris Lattner3b841e92005-12-21 02:43:26 +0000388 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
389 if (MVT::isFloatingPoint(PVT)) {
390 for (unsigned i = 0; i != NumElements; ++i) {
391 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
392 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
393 }
394 } else {
395 for (unsigned i = 0; i != NumElements; ++i) {
396 const ConstantIntegral *El =
397 cast<ConstantIntegral>(CP->getOperand(i));
398 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
399 }
400 }
401 } else {
402 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
403 SDOperand Op;
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000404 if (MVT::isFloatingPoint(PVT))
Chris Lattner3b841e92005-12-21 02:43:26 +0000405 Op = DAG.getConstantFP(0, PVT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000406 else
Chris Lattner3b841e92005-12-21 02:43:26 +0000407 Op = DAG.getConstant(0, PVT);
408 Ops.assign(NumElements, Op);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000409 }
Chris Lattner3b841e92005-12-21 02:43:26 +0000410
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000411 // Handle the case where we have a 1-element vector, in which
412 // case we want to immediately turn it into a scalar constant.
Nate Begemancc827e62005-12-07 19:48:11 +0000413 if (Ops.size() == 1) {
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000414 return N = Ops[0];
Nate Begemancc827e62005-12-07 19:48:11 +0000415 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
416 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
417 } else {
418 // If the packed type isn't legal, then create a ConstantVec node with
419 // generic Vector type instead.
Evan Cheng860771d2006-03-01 01:09:54 +0000420 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
421 SDOperand Typ = DAG.getValueType(PVT);
422 Ops.insert(Ops.begin(), Typ);
423 Ops.insert(Ops.begin(), Num);
424 return N = DAG.getNode(ISD::VConstant, MVT::Vector, Ops);
Nate Begemancc827e62005-12-07 19:48:11 +0000425 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000426 } else {
427 // Canonicalize all constant ints to be unsigned.
428 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
429 }
430
431 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
432 std::map<const AllocaInst*, int>::iterator SI =
433 FuncInfo.StaticAllocaMap.find(AI);
434 if (SI != FuncInfo.StaticAllocaMap.end())
435 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
436 }
437
438 std::map<const Value*, unsigned>::const_iterator VMI =
439 FuncInfo.ValueMap.find(V);
440 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000441
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +0000442 unsigned InReg = VMI->second;
443
444 // If this type is not legal, make it so now.
445 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
446
447 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
448 if (DestVT < VT) {
449 // Source must be expanded. This input value is actually coming from the
450 // register pair VMI->second and VMI->second+1.
451 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
452 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
453 } else {
454 if (DestVT > VT) { // Promotion case
455 if (MVT::isFloatingPoint(VT))
456 N = DAG.getNode(ISD::FP_ROUND, VT, N);
457 else
458 N = DAG.getNode(ISD::TRUNCATE, VT, N);
459 }
460 }
461
462 return N;
Chris Lattner1c08c712005-01-07 07:47:53 +0000463 }
464
465 const SDOperand &setValue(const Value *V, SDOperand NewN) {
466 SDOperand &N = NodeMap[V];
467 assert(N.Val == 0 && "Already set a value for this node!");
468 return N = NewN;
469 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000470
Chris Lattner864635a2006-02-22 22:37:12 +0000471 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
472 MVT::ValueType VT,
473 bool OutReg, bool InReg,
474 std::set<unsigned> &OutputRegs,
475 std::set<unsigned> &InputRegs);
476
Chris Lattner1c08c712005-01-07 07:47:53 +0000477 // Terminator instructions.
478 void visitRet(ReturnInst &I);
479 void visitBr(BranchInst &I);
480 void visitUnreachable(UnreachableInst &I) { /* noop */ }
481
482 // These all get lowered before this pass.
Robert Bocchinoc0f4cd92006-01-10 19:04:57 +0000483 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino4eb2e3a2006-01-17 20:06:42 +0000484 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000485 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
486 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
487 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
488
489 //
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000490 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000491 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000492 void visitAdd(User &I) {
493 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000494 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000495 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000496 void visitMul(User &I) {
497 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000498 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000499 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000500 const Type *Ty = I.getType();
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000501 visitBinary(I,
502 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
503 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner1c08c712005-01-07 07:47:53 +0000504 }
505 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000506 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000507 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000508 }
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000509 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
510 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
511 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begemane21ea612005-11-18 07:42:56 +0000512 void visitShl(User &I) { visitShift(I, ISD::SHL); }
513 void visitShr(User &I) {
514 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000515 }
516
517 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
518 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
519 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
520 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
521 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
522 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
523 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
524
525 void visitGetElementPtr(User &I);
526 void visitCast(User &I);
527 void visitSelect(User &I);
528 //
529
530 void visitMalloc(MallocInst &I);
531 void visitFree(FreeInst &I);
532 void visitAlloca(AllocaInst &I);
533 void visitLoad(LoadInst &I);
534 void visitStore(StoreInst &I);
535 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
536 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000537 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000538 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000539
Chris Lattner1c08c712005-01-07 07:47:53 +0000540 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000541 void visitVAArg(VAArgInst &I);
542 void visitVAEnd(CallInst &I);
543 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000544 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000545
Chris Lattner7041ee32005-01-11 05:56:49 +0000546 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000547
548 void visitUserOp1(Instruction &I) {
549 assert(0 && "UserOp1 should not exist at instruction selection time!");
550 abort();
551 }
552 void visitUserOp2(Instruction &I) {
553 assert(0 && "UserOp2 should not exist at instruction selection time!");
554 abort();
555 }
556};
557} // end namespace llvm
558
559void SelectionDAGLowering::visitRet(ReturnInst &I) {
560 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000561 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000562 return;
563 }
Nate Begemanee625572006-01-27 21:09:22 +0000564 std::vector<SDOperand> NewValues;
565 NewValues.push_back(getRoot());
566 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
567 SDOperand RetOp = getValue(I.getOperand(i));
568
569 // If this is an integer return value, we need to promote it ourselves to
570 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
571 // than sign/zero.
572 if (MVT::isInteger(RetOp.getValueType()) &&
573 RetOp.getValueType() < MVT::i64) {
574 MVT::ValueType TmpVT;
575 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
576 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
577 else
578 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000579
Nate Begemanee625572006-01-27 21:09:22 +0000580 if (I.getOperand(i)->getType()->isSigned())
581 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
582 else
583 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
584 }
585 NewValues.push_back(RetOp);
Chris Lattner1c08c712005-01-07 07:47:53 +0000586 }
Nate Begemanee625572006-01-27 21:09:22 +0000587 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner1c08c712005-01-07 07:47:53 +0000588}
589
590void SelectionDAGLowering::visitBr(BranchInst &I) {
591 // Update machine-CFG edges.
592 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000593
594 // Figure out which block is immediately after the current one.
595 MachineBasicBlock *NextBlock = 0;
596 MachineFunction::iterator BBI = CurMBB;
597 if (++BBI != CurMBB->getParent()->end())
598 NextBlock = BBI;
599
600 if (I.isUnconditional()) {
601 // If this is not a fall-through branch, emit the branch.
602 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000603 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000604 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000605 } else {
606 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000607
608 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000609 if (Succ1MBB == NextBlock) {
610 // If the condition is false, fall through. This means we should branch
611 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000612 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000613 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000614 } else if (Succ0MBB == NextBlock) {
615 // If the condition is true, fall through. This means we should branch if
616 // the condition is false to Succ #1. Invert the condition first.
617 SDOperand True = DAG.getConstant(1, Cond.getValueType());
618 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000619 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000620 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000621 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000622 std::vector<SDOperand> Ops;
623 Ops.push_back(getRoot());
Evan Cheng298ebf22006-02-16 08:27:56 +0000624 // If the false case is the current basic block, then this is a self
625 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
626 // adds an extra instruction in the loop. Instead, invert the
627 // condition and emit "Loop: ... br!cond Loop; br Out.
628 if (CurMBB == Succ1MBB) {
629 std::swap(Succ0MBB, Succ1MBB);
630 SDOperand True = DAG.getConstant(1, Cond.getValueType());
631 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
632 }
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000633 Ops.push_back(Cond);
634 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
635 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
636 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000637 }
638 }
639}
640
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000641void SelectionDAGLowering::visitSub(User &I) {
642 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +0000643 if (I.getType()->isFloatingPoint()) {
644 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
645 if (CFP->isExactlyValue(-0.0)) {
646 SDOperand Op2 = getValue(I.getOperand(1));
647 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
648 return;
649 }
Chris Lattner01b3d732005-09-28 22:28:18 +0000650 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000651 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000652}
653
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000654void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
655 unsigned VecOp) {
656 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +0000657 SDOperand Op1 = getValue(I.getOperand(0));
658 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000659
Chris Lattnerb67eb912005-11-19 18:40:42 +0000660 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000661 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
662 } else if (Ty->isFloatingPoint()) {
663 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
664 } else {
665 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000666 unsigned NumElements = PTy->getNumElements();
667 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000668 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000669
670 // Immediately scalarize packed types containing only one element, so that
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000671 // the Legalize pass does not have to deal with them. Similarly, if the
672 // abstract vector is going to turn into one that the target natively
673 // supports, generate that type now so that Legalize doesn't have to deal
674 // with that either. These steps ensure that Legalize only has to handle
675 // vector types in its Expand case.
676 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman4ef3b812005-11-22 01:29:36 +0000677 if (NumElements == 1) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000678 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Evan Cheng860771d2006-03-01 01:09:54 +0000679 } else if (TVT != MVT::Other &&
680 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(Opc, TVT)) {
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000681 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000682 } else {
683 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
684 SDOperand Typ = DAG.getValueType(PVT);
Evan Cheng860771d2006-03-01 01:09:54 +0000685 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Num, Typ, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000686 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000687 }
Nate Begemane21ea612005-11-18 07:42:56 +0000688}
Chris Lattner2c49f272005-01-19 22:31:21 +0000689
Nate Begemane21ea612005-11-18 07:42:56 +0000690void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
691 SDOperand Op1 = getValue(I.getOperand(0));
692 SDOperand Op2 = getValue(I.getOperand(1));
693
694 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
695
Chris Lattner1c08c712005-01-07 07:47:53 +0000696 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
697}
698
699void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
700 ISD::CondCode UnsignedOpcode) {
701 SDOperand Op1 = getValue(I.getOperand(0));
702 SDOperand Op2 = getValue(I.getOperand(1));
703 ISD::CondCode Opcode = SignedOpcode;
704 if (I.getOperand(0)->getType()->isUnsigned())
705 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000706 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000707}
708
709void SelectionDAGLowering::visitSelect(User &I) {
710 SDOperand Cond = getValue(I.getOperand(0));
711 SDOperand TrueVal = getValue(I.getOperand(1));
712 SDOperand FalseVal = getValue(I.getOperand(2));
713 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
714 TrueVal, FalseVal));
715}
716
717void SelectionDAGLowering::visitCast(User &I) {
718 SDOperand N = getValue(I.getOperand(0));
719 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
720 MVT::ValueType DestTy = TLI.getValueType(I.getType());
721
722 if (N.getValueType() == DestTy) {
723 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000724 } else if (DestTy == MVT::i1) {
725 // Cast to bool is a comparison against zero, not truncation to zero.
726 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
727 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000728 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000729 } else if (isInteger(SrcTy)) {
730 if (isInteger(DestTy)) { // Int -> Int cast
731 if (DestTy < SrcTy) // Truncating cast?
732 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
733 else if (I.getOperand(0)->getType()->isSigned())
734 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
735 else
736 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
737 } else { // Int -> FP cast
738 if (I.getOperand(0)->getType()->isSigned())
739 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
740 else
741 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
742 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000743 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000744 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
745 if (isFloatingPoint(DestTy)) { // FP -> FP cast
746 if (DestTy < SrcTy) // Rounding cast?
747 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
748 else
749 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
750 } else { // FP -> Int cast.
751 if (I.getType()->isSigned())
752 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
753 else
754 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
755 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000756 }
757}
758
759void SelectionDAGLowering::visitGetElementPtr(User &I) {
760 SDOperand N = getValue(I.getOperand(0));
761 const Type *Ty = I.getOperand(0)->getType();
762 const Type *UIntPtrTy = TD.getIntPtrType();
763
764 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
765 OI != E; ++OI) {
766 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +0000767 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000768 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
769 if (Field) {
770 // N = N + Offset
771 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
772 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000773 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000774 }
775 Ty = StTy->getElementType(Field);
776 } else {
777 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +0000778
Chris Lattner7c0104b2005-11-09 04:45:33 +0000779 // If this is a constant subscript, handle it quickly.
780 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
781 if (CI->getRawValue() == 0) continue;
Chris Lattner7cc47772005-01-07 21:56:57 +0000782
Chris Lattner7c0104b2005-11-09 04:45:33 +0000783 uint64_t Offs;
784 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
785 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
786 else
787 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
788 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
789 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +0000790 }
Chris Lattner7c0104b2005-11-09 04:45:33 +0000791
792 // N = N + Idx * ElementSize;
793 uint64_t ElementSize = TD.getTypeSize(Ty);
794 SDOperand IdxN = getValue(Idx);
795
796 // If the index is smaller or larger than intptr_t, truncate or extend
797 // it.
798 if (IdxN.getValueType() < N.getValueType()) {
799 if (Idx->getType()->isSigned())
800 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
801 else
802 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
803 } else if (IdxN.getValueType() > N.getValueType())
804 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
805
806 // If this is a multiply by a power of two, turn it into a shl
807 // immediately. This is a very common case.
808 if (isPowerOf2_64(ElementSize)) {
809 unsigned Amt = Log2_64(ElementSize);
810 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +0000811 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +0000812 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
813 continue;
814 }
815
816 SDOperand Scale = getIntPtrConstant(ElementSize);
817 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
818 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +0000819 }
820 }
821 setValue(&I, N);
822}
823
824void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
825 // If this is a fixed sized alloca in the entry block of the function,
826 // allocate it statically on the stack.
827 if (FuncInfo.StaticAllocaMap.count(&I))
828 return; // getValue will auto-populate this.
829
830 const Type *Ty = I.getAllocatedType();
831 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000832 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
833 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +0000834
835 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000836 MVT::ValueType IntPtr = TLI.getPointerTy();
837 if (IntPtr < AllocSize.getValueType())
838 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
839 else if (IntPtr > AllocSize.getValueType())
840 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000841
Chris Lattner68cd65e2005-01-22 23:04:37 +0000842 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000843 getIntPtrConstant(TySize));
844
845 // Handle alignment. If the requested alignment is less than or equal to the
846 // stack alignment, ignore it and round the size of the allocation up to the
847 // stack alignment size. If the size is greater than the stack alignment, we
848 // note this in the DYNAMIC_STACKALLOC node.
849 unsigned StackAlign =
850 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
851 if (Align <= StackAlign) {
852 Align = 0;
853 // Add SA-1 to the size.
854 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
855 getIntPtrConstant(StackAlign-1));
856 // Mask out the low bits for alignment purposes.
857 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
858 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
859 }
860
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000861 std::vector<MVT::ValueType> VTs;
862 VTs.push_back(AllocSize.getValueType());
863 VTs.push_back(MVT::Other);
864 std::vector<SDOperand> Ops;
865 Ops.push_back(getRoot());
866 Ops.push_back(AllocSize);
867 Ops.push_back(getIntPtrConstant(Align));
868 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000869 DAG.setRoot(setValue(&I, DSA).getValue(1));
870
871 // Inform the Frame Information that we have just allocated a variable-sized
872 // object.
873 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
874}
875
Chris Lattner36ce6912005-11-29 06:21:05 +0000876/// getStringValue - Turn an LLVM constant pointer that eventually points to a
877/// global into a string value. Return an empty string if we can't do it.
878///
Evan Cheng74d0aa92006-02-15 21:59:04 +0000879static std::string getStringValue(GlobalVariable *GV, unsigned Offset = 0) {
880 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
881 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
882 if (Init->isString()) {
883 std::string Result = Init->getAsString();
884 if (Offset < Result.size()) {
885 // If we are pointing INTO The string, erase the beginning...
886 Result.erase(Result.begin(), Result.begin()+Offset);
887 return Result;
Chris Lattner36ce6912005-11-29 06:21:05 +0000888 }
889 }
890 }
891 return "";
892}
Chris Lattner1c08c712005-01-07 07:47:53 +0000893
894void SelectionDAGLowering::visitLoad(LoadInst &I) {
895 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000896
Chris Lattnerd3948112005-01-17 22:19:26 +0000897 SDOperand Root;
898 if (I.isVolatile())
899 Root = getRoot();
900 else {
901 // Do not serialize non-volatile loads against each other.
902 Root = DAG.getRoot();
903 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000904
905 const Type *Ty = I.getType();
906 SDOperand L;
907
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000908 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000909 unsigned NumElements = PTy->getNumElements();
910 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000911 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000912
913 // Immediately scalarize packed types containing only one element, so that
914 // the Legalize pass does not have to deal with them.
915 if (NumElements == 1) {
916 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Evan Cheng860771d2006-03-01 01:09:54 +0000917 } else if (TVT != MVT::Other &&
918 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(ISD::LOAD, TVT)) {
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000919 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000920 } else {
921 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
922 DAG.getSrcValue(I.getOperand(0)));
923 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000924 } else {
925 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
926 DAG.getSrcValue(I.getOperand(0)));
927 }
Chris Lattnerd3948112005-01-17 22:19:26 +0000928 setValue(&I, L);
929
930 if (I.isVolatile())
931 DAG.setRoot(L.getValue(1));
932 else
933 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000934}
935
936
937void SelectionDAGLowering::visitStore(StoreInst &I) {
938 Value *SrcV = I.getOperand(0);
939 SDOperand Src = getValue(SrcV);
940 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000941 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000942 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000943}
944
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000945/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
946/// we want to emit this as a call to a named external function, return the name
947/// otherwise lower it and return null.
948const char *
949SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
950 switch (Intrinsic) {
951 case Intrinsic::vastart: visitVAStart(I); return 0;
952 case Intrinsic::vaend: visitVAEnd(I); return 0;
953 case Intrinsic::vacopy: visitVACopy(I); return 0;
954 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
955 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
956 case Intrinsic::setjmp:
957 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
958 break;
959 case Intrinsic::longjmp:
960 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
961 break;
Chris Lattner03dd4652006-03-03 00:00:25 +0000962 case Intrinsic::memcpy_i32:
963 case Intrinsic::memcpy_i64:
964 visitMemIntrinsic(I, ISD::MEMCPY);
965 return 0;
966 case Intrinsic::memset_i32:
967 case Intrinsic::memset_i64:
968 visitMemIntrinsic(I, ISD::MEMSET);
969 return 0;
970 case Intrinsic::memmove_i32:
971 case Intrinsic::memmove_i64:
972 visitMemIntrinsic(I, ISD::MEMMOVE);
973 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000974
Chris Lattner86cb6432005-12-13 17:40:33 +0000975 case Intrinsic::dbg_stoppoint: {
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000976 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
977 return "llvm_debugger_stop";
Chris Lattner36ce6912005-11-29 06:21:05 +0000978
Jim Laskeyce72b172006-02-11 01:01:30 +0000979 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
980 if (DebugInfo && DebugInfo->Verify(I.getOperand(4))) {
981 std::vector<SDOperand> Ops;
Chris Lattner36ce6912005-11-29 06:21:05 +0000982
Jim Laskeyce72b172006-02-11 01:01:30 +0000983 // Input Chain
984 Ops.push_back(getRoot());
985
986 // line number
987 Ops.push_back(getValue(I.getOperand(2)));
988
989 // column
990 Ops.push_back(getValue(I.getOperand(3)));
Chris Lattner36ce6912005-11-29 06:21:05 +0000991
Jim Laskeyd96185a2006-02-13 12:50:39 +0000992 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4));
Jim Laskeyce72b172006-02-11 01:01:30 +0000993 assert(DD && "Not a debug information descriptor");
994 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
995 assert(CompileUnit && "Not a compile unit");
996 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
997 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
998
999 if (Ops.size() == 5) // Found filename/workingdir.
1000 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner86cb6432005-12-13 17:40:33 +00001001 }
1002
Chris Lattnerd67b3a82005-12-03 18:50:48 +00001003 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001004 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00001005 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001006 case Intrinsic::dbg_region_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001007 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1008 return "llvm_dbg_region_start";
1009 if (I.getType() != Type::VoidTy)
1010 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1011 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001012 case Intrinsic::dbg_region_end:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001013 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1014 return "llvm_dbg_region_end";
1015 if (I.getType() != Type::VoidTy)
1016 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1017 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001018 case Intrinsic::dbg_func_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001019 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1020 return "llvm_dbg_subprogram";
1021 if (I.getType() != Type::VoidTy)
1022 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1023 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001024 case Intrinsic::dbg_declare:
1025 if (I.getType() != Type::VoidTy)
1026 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1027 return 0;
1028
Reid Spencer0b118202006-01-16 21:12:35 +00001029 case Intrinsic::isunordered_f32:
1030 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001031 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1032 getValue(I.getOperand(2)), ISD::SETUO));
1033 return 0;
1034
Reid Spencer0b118202006-01-16 21:12:35 +00001035 case Intrinsic::sqrt_f32:
1036 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001037 setValue(&I, DAG.getNode(ISD::FSQRT,
1038 getValue(I.getOperand(1)).getValueType(),
1039 getValue(I.getOperand(1))));
1040 return 0;
1041 case Intrinsic::pcmarker: {
1042 SDOperand Tmp = getValue(I.getOperand(1));
1043 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1044 return 0;
1045 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001046 case Intrinsic::readcyclecounter: {
1047 std::vector<MVT::ValueType> VTs;
1048 VTs.push_back(MVT::i64);
1049 VTs.push_back(MVT::Other);
1050 std::vector<SDOperand> Ops;
1051 Ops.push_back(getRoot());
1052 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1053 setValue(&I, Tmp);
1054 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001055 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001056 }
Nate Begemand88fc032006-01-14 03:14:10 +00001057 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001058 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001059 case Intrinsic::bswap_i64:
1060 setValue(&I, DAG.getNode(ISD::BSWAP,
1061 getValue(I.getOperand(1)).getValueType(),
1062 getValue(I.getOperand(1))));
1063 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001064 case Intrinsic::cttz_i8:
1065 case Intrinsic::cttz_i16:
1066 case Intrinsic::cttz_i32:
1067 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001068 setValue(&I, DAG.getNode(ISD::CTTZ,
1069 getValue(I.getOperand(1)).getValueType(),
1070 getValue(I.getOperand(1))));
1071 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001072 case Intrinsic::ctlz_i8:
1073 case Intrinsic::ctlz_i16:
1074 case Intrinsic::ctlz_i32:
1075 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001076 setValue(&I, DAG.getNode(ISD::CTLZ,
1077 getValue(I.getOperand(1)).getValueType(),
1078 getValue(I.getOperand(1))));
1079 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001080 case Intrinsic::ctpop_i8:
1081 case Intrinsic::ctpop_i16:
1082 case Intrinsic::ctpop_i32:
1083 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001084 setValue(&I, DAG.getNode(ISD::CTPOP,
1085 getValue(I.getOperand(1)).getValueType(),
1086 getValue(I.getOperand(1))));
1087 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001088 case Intrinsic::stacksave: {
1089 std::vector<MVT::ValueType> VTs;
1090 VTs.push_back(TLI.getPointerTy());
1091 VTs.push_back(MVT::Other);
1092 std::vector<SDOperand> Ops;
1093 Ops.push_back(getRoot());
1094 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1095 setValue(&I, Tmp);
1096 DAG.setRoot(Tmp.getValue(1));
1097 return 0;
1098 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00001099 case Intrinsic::stackrestore: {
1100 SDOperand Tmp = getValue(I.getOperand(1));
1101 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00001102 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00001103 }
Chris Lattnerac22c832005-12-12 22:51:16 +00001104 case Intrinsic::prefetch:
1105 // FIXME: Currently discarding prefetches.
1106 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001107 default:
1108 std::cerr << I;
1109 assert(0 && "This intrinsic is not implemented yet!");
1110 return 0;
1111 }
1112}
1113
1114
Chris Lattner1c08c712005-01-07 07:47:53 +00001115void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001116 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001117 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001118 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001119 if (unsigned IID = F->getIntrinsicID()) {
1120 RenameFn = visitIntrinsicCall(I, IID);
1121 if (!RenameFn)
1122 return;
1123 } else { // Not an LLVM intrinsic.
1124 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00001125 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1126 if (I.getNumOperands() == 3 && // Basic sanity checks.
1127 I.getOperand(1)->getType()->isFloatingPoint() &&
1128 I.getType() == I.getOperand(1)->getType() &&
1129 I.getType() == I.getOperand(2)->getType()) {
1130 SDOperand LHS = getValue(I.getOperand(1));
1131 SDOperand RHS = getValue(I.getOperand(2));
1132 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1133 LHS, RHS));
1134 return;
1135 }
1136 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001137 if (I.getNumOperands() == 2 && // Basic sanity checks.
1138 I.getOperand(1)->getType()->isFloatingPoint() &&
1139 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001140 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001141 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1142 return;
1143 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001144 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001145 if (I.getNumOperands() == 2 && // Basic sanity checks.
1146 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001147 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001148 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001149 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1150 return;
1151 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001152 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001153 if (I.getNumOperands() == 2 && // Basic sanity checks.
1154 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001155 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001156 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001157 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1158 return;
1159 }
1160 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001161 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001162 } else if (isa<InlineAsm>(I.getOperand(0))) {
1163 visitInlineAsm(I);
1164 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001165 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001166
Chris Lattner64e14b12005-01-08 22:48:57 +00001167 SDOperand Callee;
1168 if (!RenameFn)
1169 Callee = getValue(I.getOperand(0));
1170 else
1171 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001172 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001173 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001174 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1175 Value *Arg = I.getOperand(i);
1176 SDOperand ArgNode = getValue(Arg);
1177 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1178 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001179
Nate Begeman8e21e712005-03-26 01:29:23 +00001180 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1181 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001182
Chris Lattnercf5734d2005-01-08 19:26:18 +00001183 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001184 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001185 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001186 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001187 setValue(&I, Result.first);
1188 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001189}
1190
Chris Lattner864635a2006-02-22 22:37:12 +00001191SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001192 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00001193 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1194 Chain = Val.getValue(1);
1195 Flag = Val.getValue(2);
1196
1197 // If the result was expanded, copy from the top part.
1198 if (Regs.size() > 1) {
1199 assert(Regs.size() == 2 &&
1200 "Cannot expand to more than 2 elts yet!");
1201 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1202 Chain = Val.getValue(1);
1203 Flag = Val.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00001204 if (DAG.getTargetLoweringInfo().isLittleEndian())
1205 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1206 else
1207 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00001208 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00001209
Chris Lattner864635a2006-02-22 22:37:12 +00001210 // Otherwise, if the return value was promoted, truncate it to the
1211 // appropriate type.
1212 if (RegVT == ValueVT)
1213 return Val;
1214
1215 if (MVT::isInteger(RegVT))
1216 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1217 else
1218 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1219}
1220
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001221/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1222/// specified value into the registers specified by this object. This uses
1223/// Chain/Flag as the input and updates them for the output Chain/Flag.
1224void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001225 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001226 if (Regs.size() == 1) {
1227 // If there is a single register and the types differ, this must be
1228 // a promotion.
1229 if (RegVT != ValueVT) {
1230 if (MVT::isInteger(RegVT))
1231 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1232 else
1233 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1234 }
1235 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1236 Flag = Chain.getValue(1);
1237 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00001238 std::vector<unsigned> R(Regs);
1239 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1240 std::reverse(R.begin(), R.end());
1241
1242 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001243 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1244 DAG.getConstant(i, MVT::i32));
Chris Lattner9f6637d2006-02-23 20:06:57 +00001245 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001246 Flag = Chain.getValue(1);
1247 }
1248 }
1249}
Chris Lattner864635a2006-02-22 22:37:12 +00001250
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001251/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1252/// operand list. This adds the code marker and includes the number of
1253/// values added into it.
1254void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001255 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001256 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1257 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1258 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1259}
Chris Lattner864635a2006-02-22 22:37:12 +00001260
1261/// isAllocatableRegister - If the specified register is safe to allocate,
1262/// i.e. it isn't a stack pointer or some other special register, return the
1263/// register class for the register. Otherwise, return null.
1264static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001265isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1266 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1267 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1268 E = MRI->regclass_end(); RCI != E; ++RCI) {
1269 const TargetRegisterClass *RC = *RCI;
1270 // If none of the the value types for this register class are valid, we
1271 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1272 bool isLegal = false;
1273 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1274 I != E; ++I) {
1275 if (TLI.isTypeLegal(*I)) {
1276 isLegal = true;
1277 break;
1278 }
1279 }
1280
1281 if (!isLegal) continue;
1282
Chris Lattner864635a2006-02-22 22:37:12 +00001283 // NOTE: This isn't ideal. In particular, this might allocate the
1284 // frame pointer in functions that need it (due to them not being taken
1285 // out of allocation, because a variable sized allocation hasn't been seen
1286 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001287 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1288 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner864635a2006-02-22 22:37:12 +00001289 if (*I == Reg)
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001290 return RC;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001291 }
1292 return 0;
Chris Lattner864635a2006-02-22 22:37:12 +00001293}
1294
1295RegsForValue SelectionDAGLowering::
1296GetRegistersForValue(const std::string &ConstrCode,
1297 MVT::ValueType VT, bool isOutReg, bool isInReg,
1298 std::set<unsigned> &OutputRegs,
1299 std::set<unsigned> &InputRegs) {
1300 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1301 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1302 std::vector<unsigned> Regs;
1303
1304 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1305 MVT::ValueType RegVT;
1306 MVT::ValueType ValueVT = VT;
1307
1308 if (PhysReg.first) {
1309 if (VT == MVT::Other)
1310 ValueVT = *PhysReg.second->vt_begin();
1311 RegVT = VT;
1312
1313 // This is a explicit reference to a physical register.
1314 Regs.push_back(PhysReg.first);
1315
1316 // If this is an expanded reference, add the rest of the regs to Regs.
1317 if (NumRegs != 1) {
1318 RegVT = *PhysReg.second->vt_begin();
1319 TargetRegisterClass::iterator I = PhysReg.second->begin();
1320 TargetRegisterClass::iterator E = PhysReg.second->end();
1321 for (; *I != PhysReg.first; ++I)
1322 assert(I != E && "Didn't find reg!");
1323
1324 // Already added the first reg.
1325 --NumRegs; ++I;
1326 for (; NumRegs; --NumRegs, ++I) {
1327 assert(I != E && "Ran out of registers to allocate!");
1328 Regs.push_back(*I);
1329 }
1330 }
1331 return RegsForValue(Regs, RegVT, ValueVT);
1332 }
1333
1334 // This is a reference to a register class. Allocate NumRegs consecutive,
1335 // available, registers from the class.
1336 std::vector<unsigned> RegClassRegs =
1337 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1338
1339 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1340 MachineFunction &MF = *CurMBB->getParent();
1341 unsigned NumAllocated = 0;
1342 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1343 unsigned Reg = RegClassRegs[i];
1344 // See if this register is available.
1345 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1346 (isInReg && InputRegs.count(Reg))) { // Already used.
1347 // Make sure we find consecutive registers.
1348 NumAllocated = 0;
1349 continue;
1350 }
1351
1352 // Check to see if this register is allocatable (i.e. don't give out the
1353 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001354 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00001355 if (!RC) {
1356 // Make sure we find consecutive registers.
1357 NumAllocated = 0;
1358 continue;
1359 }
1360
1361 // Okay, this register is good, we can use it.
1362 ++NumAllocated;
1363
1364 // If we allocated enough consecutive
1365 if (NumAllocated == NumRegs) {
1366 unsigned RegStart = (i-NumAllocated)+1;
1367 unsigned RegEnd = i+1;
1368 // Mark all of the allocated registers used.
1369 for (unsigned i = RegStart; i != RegEnd; ++i) {
1370 unsigned Reg = RegClassRegs[i];
1371 Regs.push_back(Reg);
1372 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1373 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1374 }
1375
1376 return RegsForValue(Regs, *RC->vt_begin(), VT);
1377 }
1378 }
1379
1380 // Otherwise, we couldn't allocate enough registers for this.
1381 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00001382}
1383
Chris Lattner864635a2006-02-22 22:37:12 +00001384
Chris Lattnerce7518c2006-01-26 22:24:51 +00001385/// visitInlineAsm - Handle a call to an InlineAsm object.
1386///
1387void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1388 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1389
1390 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1391 MVT::Other);
1392
1393 // Note, we treat inline asms both with and without side-effects as the same.
1394 // If an inline asm doesn't have side effects and doesn't access memory, we
1395 // could not choose to not chain it.
1396 bool hasSideEffects = IA->hasSideEffects();
1397
Chris Lattner2cc2f662006-02-01 01:28:23 +00001398 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001399 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00001400
1401 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1402 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1403 /// if it is a def of that register.
1404 std::vector<SDOperand> AsmNodeOperands;
1405 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1406 AsmNodeOperands.push_back(AsmStr);
1407
1408 SDOperand Chain = getRoot();
1409 SDOperand Flag;
1410
Chris Lattner4e4b5762006-02-01 18:59:47 +00001411 // We fully assign registers here at isel time. This is not optimal, but
1412 // should work. For register classes that correspond to LLVM classes, we
1413 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1414 // over the constraints, collecting fixed registers that we know we can't use.
1415 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001416 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001417 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1418 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1419 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00001420
Chris Lattner1efa40f2006-02-22 00:56:39 +00001421 MVT::ValueType OpVT;
1422
1423 // Compute the value type for each operand and add it to ConstraintVTs.
1424 switch (Constraints[i].Type) {
1425 case InlineAsm::isOutput:
1426 if (!Constraints[i].isIndirectOutput) {
1427 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1428 OpVT = TLI.getValueType(I.getType());
1429 } else {
Chris Lattner22873462006-02-27 23:45:39 +00001430 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001431 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1432 OpNum++; // Consumes a call operand.
1433 }
1434 break;
1435 case InlineAsm::isInput:
1436 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1437 OpNum++; // Consumes a call operand.
1438 break;
1439 case InlineAsm::isClobber:
1440 OpVT = MVT::Other;
1441 break;
1442 }
1443
1444 ConstraintVTs.push_back(OpVT);
1445
Chris Lattner864635a2006-02-22 22:37:12 +00001446 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1447 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00001448
Chris Lattner864635a2006-02-22 22:37:12 +00001449 // Build a list of regs that this operand uses. This always has a single
1450 // element for promoted/expanded operands.
1451 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1452 false, false,
1453 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00001454
1455 switch (Constraints[i].Type) {
1456 case InlineAsm::isOutput:
1457 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001458 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001459 // If this is an early-clobber output, it cannot be assigned to the same
1460 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00001461 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00001462 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001463 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001464 case InlineAsm::isInput:
1465 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001466 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00001467 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001468 case InlineAsm::isClobber:
1469 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00001470 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1471 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001472 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001473 }
1474 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00001475
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001476 // Loop over all of the inputs, copying the operand values into the
1477 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00001478 RegsForValue RetValRegs;
1479 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001480 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001481
Chris Lattner6656dd12006-01-31 02:03:41 +00001482 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00001483 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1484 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00001485
Chris Lattner2cc2f662006-02-01 01:28:23 +00001486 switch (Constraints[i].Type) {
1487 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00001488 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1489 if (ConstraintCode.size() == 1) // not a physreg name.
1490 CTy = TLI.getConstraintType(ConstraintCode[0]);
1491
1492 if (CTy == TargetLowering::C_Memory) {
1493 // Memory output.
1494 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1495
1496 // Check that the operand (the address to store to) isn't a float.
1497 if (!MVT::isInteger(InOperandVal.getValueType()))
1498 assert(0 && "MATCH FAIL!");
1499
1500 if (!Constraints[i].isIndirectOutput)
1501 assert(0 && "MATCH FAIL!");
1502
1503 OpNum++; // Consumes a call operand.
1504
1505 // Extend/truncate to the right pointer type if needed.
1506 MVT::ValueType PtrType = TLI.getPointerTy();
1507 if (InOperandVal.getValueType() < PtrType)
1508 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1509 else if (InOperandVal.getValueType() > PtrType)
1510 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1511
1512 // Add information to the INLINEASM node to know about this output.
1513 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1514 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1515 AsmNodeOperands.push_back(InOperandVal);
1516 break;
1517 }
1518
1519 // Otherwise, this is a register output.
1520 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1521
Chris Lattner864635a2006-02-22 22:37:12 +00001522 // If this is an early-clobber output, or if there is an input
1523 // constraint that matches this, we need to reserve the input register
1524 // so no other inputs allocate to it.
1525 bool UsesInputRegister = false;
1526 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1527 UsesInputRegister = true;
1528
1529 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00001530 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00001531 RegsForValue Regs =
1532 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1533 true, UsesInputRegister,
1534 OutputRegs, InputRegs);
1535 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner1efa40f2006-02-22 00:56:39 +00001536
Chris Lattner2cc2f662006-02-01 01:28:23 +00001537 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00001538 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00001539 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00001540 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00001541 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00001542 } else {
Chris Lattner22873462006-02-27 23:45:39 +00001543 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1544 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00001545 OpNum++; // Consumes a call operand.
1546 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001547
1548 // Add information to the INLINEASM node to know that this register is
1549 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001550 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001551 break;
1552 }
1553 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00001554 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00001555 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00001556
Chris Lattner2223aea2006-02-02 00:25:23 +00001557 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1558 // If this is required to match an output register we have already set,
1559 // just use its register.
1560 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00001561
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001562 // Scan until we find the definition we already emitted of this operand.
1563 // When we find it, create a RegsForValue operand.
1564 unsigned CurOp = 2; // The first operand.
1565 for (; OperandNo; --OperandNo) {
1566 // Advance to the next operand.
1567 unsigned NumOps =
1568 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1569 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1570 "Skipped past definitions?");
1571 CurOp += (NumOps>>3)+1;
1572 }
1573
1574 unsigned NumOps =
1575 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1576 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1577 "Skipped past definitions?");
1578
1579 // Add NumOps>>3 registers to MatchedRegs.
1580 RegsForValue MatchedRegs;
1581 MatchedRegs.ValueVT = InOperandVal.getValueType();
1582 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1583 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1584 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1585 MatchedRegs.Regs.push_back(Reg);
1586 }
1587
1588 // Use the produced MatchedRegs object to
1589 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1590 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001591 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00001592 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00001593
1594 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1595 if (ConstraintCode.size() == 1) // not a physreg name.
1596 CTy = TLI.getConstraintType(ConstraintCode[0]);
1597
1598 if (CTy == TargetLowering::C_Other) {
1599 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1600 assert(0 && "MATCH FAIL!");
1601
1602 // Add information to the INLINEASM node to know about this input.
1603 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1604 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1605 AsmNodeOperands.push_back(InOperandVal);
1606 break;
1607 } else if (CTy == TargetLowering::C_Memory) {
1608 // Memory input.
1609
1610 // Check that the operand isn't a float.
1611 if (!MVT::isInteger(InOperandVal.getValueType()))
1612 assert(0 && "MATCH FAIL!");
1613
1614 // Extend/truncate to the right pointer type if needed.
1615 MVT::ValueType PtrType = TLI.getPointerTy();
1616 if (InOperandVal.getValueType() < PtrType)
1617 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1618 else if (InOperandVal.getValueType() > PtrType)
1619 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1620
1621 // Add information to the INLINEASM node to know about this input.
1622 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1623 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1624 AsmNodeOperands.push_back(InOperandVal);
1625 break;
1626 }
1627
1628 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1629
1630 // Copy the input into the appropriate registers.
1631 RegsForValue InRegs =
1632 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1633 false, true, OutputRegs, InputRegs);
1634 // FIXME: should be match fail.
1635 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1636
1637 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1638
1639 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001640 break;
1641 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001642 case InlineAsm::isClobber: {
1643 RegsForValue ClobberedRegs =
1644 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1645 OutputRegs, InputRegs);
1646 // Add the clobbered value to the operand list, so that the register
1647 // allocator is aware that the physreg got clobbered.
1648 if (!ClobberedRegs.Regs.empty())
1649 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001650 break;
1651 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001652 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001653 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001654
1655 // Finish up input operands.
1656 AsmNodeOperands[0] = Chain;
1657 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1658
1659 std::vector<MVT::ValueType> VTs;
1660 VTs.push_back(MVT::Other);
1661 VTs.push_back(MVT::Flag);
1662 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1663 Flag = Chain.getValue(1);
1664
Chris Lattner6656dd12006-01-31 02:03:41 +00001665 // If this asm returns a register value, copy the result from that register
1666 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00001667 if (!RetValRegs.Regs.empty())
1668 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00001669
Chris Lattner6656dd12006-01-31 02:03:41 +00001670 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1671
1672 // Process indirect outputs, first output all of the flagged copies out of
1673 // physregs.
1674 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00001675 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00001676 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00001677 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1678 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00001679 }
1680
1681 // Emit the non-flagged stores from the physregs.
1682 std::vector<SDOperand> OutChains;
1683 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1684 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1685 StoresToEmit[i].first,
1686 getValue(StoresToEmit[i].second),
1687 DAG.getSrcValue(StoresToEmit[i].second)));
1688 if (!OutChains.empty())
1689 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattnerce7518c2006-01-26 22:24:51 +00001690 DAG.setRoot(Chain);
1691}
1692
1693
Chris Lattner1c08c712005-01-07 07:47:53 +00001694void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1695 SDOperand Src = getValue(I.getOperand(0));
1696
1697 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00001698
1699 if (IntPtr < Src.getValueType())
1700 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1701 else if (IntPtr > Src.getValueType())
1702 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00001703
1704 // Scale the source by the type size.
1705 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1706 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1707 Src, getIntPtrConstant(ElementSize));
1708
1709 std::vector<std::pair<SDOperand, const Type*> > Args;
1710 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00001711
1712 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001713 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001714 DAG.getExternalSymbol("malloc", IntPtr),
1715 Args, DAG);
1716 setValue(&I, Result.first); // Pointers always fit in registers
1717 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001718}
1719
1720void SelectionDAGLowering::visitFree(FreeInst &I) {
1721 std::vector<std::pair<SDOperand, const Type*> > Args;
1722 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1723 TLI.getTargetData().getIntPtrType()));
1724 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00001725 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001726 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001727 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1728 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001729}
1730
Chris Lattner025c39b2005-08-26 20:54:47 +00001731// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1732// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1733// instructions are special in various ways, which require special support to
1734// insert. The specified MachineInstr is created but not inserted into any
1735// basic blocks, and the scheduler passes ownership of it to this method.
1736MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1737 MachineBasicBlock *MBB) {
1738 std::cerr << "If a target marks an instruction with "
1739 "'usesCustomDAGSchedInserter', it must implement "
1740 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1741 abort();
1742 return 0;
1743}
1744
Chris Lattner39ae3622005-01-09 00:00:49 +00001745void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001746 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1747 getValue(I.getOperand(1)),
1748 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00001749}
1750
1751void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001752 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1753 getValue(I.getOperand(0)),
1754 DAG.getSrcValue(I.getOperand(0)));
1755 setValue(&I, V);
1756 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00001757}
1758
1759void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001760 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1761 getValue(I.getOperand(1)),
1762 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001763}
1764
1765void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001766 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1767 getValue(I.getOperand(1)),
1768 getValue(I.getOperand(2)),
1769 DAG.getSrcValue(I.getOperand(1)),
1770 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001771}
1772
Chris Lattner39ae3622005-01-09 00:00:49 +00001773// It is always conservatively correct for llvm.returnaddress and
1774// llvm.frameaddress to return 0.
1775std::pair<SDOperand, SDOperand>
1776TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1777 unsigned Depth, SelectionDAG &DAG) {
1778 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00001779}
1780
Chris Lattner50381b62005-05-14 05:50:48 +00001781SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00001782 assert(0 && "LowerOperation not implemented for this target!");
1783 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001784 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00001785}
1786
Nate Begeman0aed7842006-01-28 03:14:31 +00001787SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1788 SelectionDAG &DAG) {
1789 assert(0 && "CustomPromoteOperation not implemented for this target!");
1790 abort();
1791 return SDOperand();
1792}
1793
Chris Lattner39ae3622005-01-09 00:00:49 +00001794void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1795 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1796 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00001797 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001798 setValue(&I, Result.first);
1799 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001800}
1801
Evan Cheng74d0aa92006-02-15 21:59:04 +00001802/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00001803/// operand.
1804static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00001805 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001806 MVT::ValueType CurVT = VT;
1807 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1808 uint64_t Val = C->getValue() & 255;
1809 unsigned Shift = 8;
1810 while (CurVT != MVT::i8) {
1811 Val = (Val << Shift) | Val;
1812 Shift <<= 1;
1813 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001814 }
1815 return DAG.getConstant(Val, VT);
1816 } else {
1817 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1818 unsigned Shift = 8;
1819 while (CurVT != MVT::i8) {
1820 Value =
1821 DAG.getNode(ISD::OR, VT,
1822 DAG.getNode(ISD::SHL, VT, Value,
1823 DAG.getConstant(Shift, MVT::i8)), Value);
1824 Shift <<= 1;
1825 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001826 }
1827
1828 return Value;
1829 }
1830}
1831
Evan Cheng74d0aa92006-02-15 21:59:04 +00001832/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1833/// used when a memcpy is turned into a memset when the source is a constant
1834/// string ptr.
1835static SDOperand getMemsetStringVal(MVT::ValueType VT,
1836 SelectionDAG &DAG, TargetLowering &TLI,
1837 std::string &Str, unsigned Offset) {
1838 MVT::ValueType CurVT = VT;
1839 uint64_t Val = 0;
1840 unsigned MSB = getSizeInBits(VT) / 8;
1841 if (TLI.isLittleEndian())
1842 Offset = Offset + MSB - 1;
1843 for (unsigned i = 0; i != MSB; ++i) {
1844 Val = (Val << 8) | Str[Offset];
1845 Offset += TLI.isLittleEndian() ? -1 : 1;
1846 }
1847 return DAG.getConstant(Val, VT);
1848}
1849
Evan Cheng1db92f92006-02-14 08:22:34 +00001850/// getMemBasePlusOffset - Returns base and offset node for the
1851static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1852 SelectionDAG &DAG, TargetLowering &TLI) {
1853 MVT::ValueType VT = Base.getValueType();
1854 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1855}
1856
Evan Chengc4f8eee2006-02-14 20:12:38 +00001857/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00001858/// to replace the memset / memcpy is below the threshold. It also returns the
1859/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00001860static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1861 unsigned Limit, uint64_t Size,
1862 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001863 MVT::ValueType VT;
1864
1865 if (TLI.allowsUnalignedMemoryAccesses()) {
1866 VT = MVT::i64;
1867 } else {
1868 switch (Align & 7) {
1869 case 0:
1870 VT = MVT::i64;
1871 break;
1872 case 4:
1873 VT = MVT::i32;
1874 break;
1875 case 2:
1876 VT = MVT::i16;
1877 break;
1878 default:
1879 VT = MVT::i8;
1880 break;
1881 }
1882 }
1883
Evan Cheng80e89d72006-02-14 09:11:59 +00001884 MVT::ValueType LVT = MVT::i64;
1885 while (!TLI.isTypeLegal(LVT))
1886 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1887 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00001888
Evan Cheng80e89d72006-02-14 09:11:59 +00001889 if (VT > LVT)
1890 VT = LVT;
1891
Evan Chengdea72452006-02-14 23:05:54 +00001892 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00001893 while (Size != 0) {
1894 unsigned VTSize = getSizeInBits(VT) / 8;
1895 while (VTSize > Size) {
1896 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001897 VTSize >>= 1;
1898 }
Evan Cheng80e89d72006-02-14 09:11:59 +00001899 assert(MVT::isInteger(VT));
1900
1901 if (++NumMemOps > Limit)
1902 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00001903 MemOps.push_back(VT);
1904 Size -= VTSize;
1905 }
Evan Cheng80e89d72006-02-14 09:11:59 +00001906
1907 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00001908}
1909
Chris Lattner7041ee32005-01-11 05:56:49 +00001910void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001911 SDOperand Op1 = getValue(I.getOperand(1));
1912 SDOperand Op2 = getValue(I.getOperand(2));
1913 SDOperand Op3 = getValue(I.getOperand(3));
1914 SDOperand Op4 = getValue(I.getOperand(4));
1915 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1916 if (Align == 0) Align = 1;
1917
1918 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1919 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00001920
1921 // Expand memset / memcpy to a series of load / store ops
1922 // if the size operand falls below a certain threshold.
1923 std::vector<SDOperand> OutChains;
1924 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00001925 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00001926 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00001927 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1928 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00001929 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00001930 unsigned Offset = 0;
1931 for (unsigned i = 0; i < NumMemOps; i++) {
1932 MVT::ValueType VT = MemOps[i];
1933 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00001934 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengc080d6f2006-02-15 01:54:51 +00001935 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1936 Value,
Chris Lattner864635a2006-02-22 22:37:12 +00001937 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1938 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chengc080d6f2006-02-15 01:54:51 +00001939 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00001940 Offset += VTSize;
1941 }
Evan Cheng1db92f92006-02-14 08:22:34 +00001942 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001943 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00001944 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001945 case ISD::MEMCPY: {
1946 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1947 Size->getValue(), Align, TLI)) {
1948 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00001949 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001950 GlobalAddressSDNode *G = NULL;
1951 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00001952 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001953
1954 if (Op2.getOpcode() == ISD::GlobalAddress)
1955 G = cast<GlobalAddressSDNode>(Op2);
1956 else if (Op2.getOpcode() == ISD::ADD &&
1957 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1958 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1959 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00001960 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00001961 }
1962 if (G) {
1963 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengcffbb512006-02-16 23:11:42 +00001964 if (GV) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00001965 Str = getStringValue(GV);
Evan Chengcffbb512006-02-16 23:11:42 +00001966 if (!Str.empty()) {
1967 CopyFromStr = true;
1968 SrcOff += SrcDelta;
1969 }
1970 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00001971 }
1972
Evan Chengc080d6f2006-02-15 01:54:51 +00001973 for (unsigned i = 0; i < NumMemOps; i++) {
1974 MVT::ValueType VT = MemOps[i];
1975 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001976 SDOperand Value, Chain, Store;
1977
Evan Chengcffbb512006-02-16 23:11:42 +00001978 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00001979 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
1980 Chain = getRoot();
1981 Store =
1982 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1983 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1984 DAG.getSrcValue(I.getOperand(1), DstOff));
1985 } else {
1986 Value = DAG.getLoad(VT, getRoot(),
1987 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
1988 DAG.getSrcValue(I.getOperand(2), SrcOff));
1989 Chain = Value.getValue(1);
1990 Store =
1991 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1992 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1993 DAG.getSrcValue(I.getOperand(1), DstOff));
1994 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001995 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00001996 SrcOff += VTSize;
1997 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00001998 }
1999 }
2000 break;
2001 }
2002 }
2003
2004 if (!OutChains.empty()) {
2005 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2006 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00002007 }
2008 }
2009
Chris Lattner7041ee32005-01-11 05:56:49 +00002010 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +00002011 Ops.push_back(getRoot());
Evan Cheng1db92f92006-02-14 08:22:34 +00002012 Ops.push_back(Op1);
2013 Ops.push_back(Op2);
2014 Ops.push_back(Op3);
2015 Ops.push_back(Op4);
Chris Lattner7041ee32005-01-11 05:56:49 +00002016 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +00002017}
2018
Chris Lattner7041ee32005-01-11 05:56:49 +00002019//===----------------------------------------------------------------------===//
2020// SelectionDAGISel code
2021//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00002022
2023unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2024 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2025}
2026
Chris Lattner495a0b52005-08-17 06:37:43 +00002027void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00002028 // FIXME: we only modify the CFG to split critical edges. This
2029 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +00002030}
Chris Lattner1c08c712005-01-07 07:47:53 +00002031
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002032
2033/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2034/// casting to the type of GEPI.
2035static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2036 Value *Ptr, Value *PtrOffset) {
2037 if (V) return V; // Already computed.
2038
2039 BasicBlock::iterator InsertPt;
2040 if (BB == GEPI->getParent()) {
2041 // If insert into the GEP's block, insert right after the GEP.
2042 InsertPt = GEPI;
2043 ++InsertPt;
2044 } else {
2045 // Otherwise, insert at the top of BB, after any PHI nodes
2046 InsertPt = BB->begin();
2047 while (isa<PHINode>(InsertPt)) ++InsertPt;
2048 }
2049
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002050 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2051 // BB so that there is only one value live across basic blocks (the cast
2052 // operand).
2053 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2054 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2055 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2056
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002057 // Add the offset, cast it to the right type.
2058 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2059 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2060 return V = Ptr;
2061}
2062
2063
2064/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2065/// selection, we want to be a bit careful about some things. In particular, if
2066/// we have a GEP instruction that is used in a different block than it is
2067/// defined, the addressing expression of the GEP cannot be folded into loads or
2068/// stores that use it. In this case, decompose the GEP and move constant
2069/// indices into blocks that use it.
2070static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2071 const TargetData &TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002072 // If this GEP is only used inside the block it is defined in, there is no
2073 // need to rewrite it.
2074 bool isUsedOutsideDefBB = false;
2075 BasicBlock *DefBB = GEPI->getParent();
2076 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2077 UI != E; ++UI) {
2078 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2079 isUsedOutsideDefBB = true;
2080 break;
2081 }
2082 }
2083 if (!isUsedOutsideDefBB) return;
2084
2085 // If this GEP has no non-zero constant indices, there is nothing we can do,
2086 // ignore it.
2087 bool hasConstantIndex = false;
2088 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2089 E = GEPI->op_end(); OI != E; ++OI) {
2090 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2091 if (CI->getRawValue()) {
2092 hasConstantIndex = true;
2093 break;
2094 }
2095 }
Chris Lattner3802c252005-12-11 09:05:13 +00002096 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2097 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002098
2099 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2100 // constant offset (which we now know is non-zero) and deal with it later.
2101 uint64_t ConstantOffset = 0;
2102 const Type *UIntPtrTy = TD.getIntPtrType();
2103 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2104 const Type *Ty = GEPI->getOperand(0)->getType();
2105
2106 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2107 E = GEPI->op_end(); OI != E; ++OI) {
2108 Value *Idx = *OI;
2109 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2110 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2111 if (Field)
2112 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2113 Ty = StTy->getElementType(Field);
2114 } else {
2115 Ty = cast<SequentialType>(Ty)->getElementType();
2116
2117 // Handle constant subscripts.
2118 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2119 if (CI->getRawValue() == 0) continue;
2120
2121 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2122 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2123 else
2124 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2125 continue;
2126 }
2127
2128 // Ptr = Ptr + Idx * ElementSize;
2129
2130 // Cast Idx to UIntPtrTy if needed.
2131 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2132
2133 uint64_t ElementSize = TD.getTypeSize(Ty);
2134 // Mask off bits that should not be set.
2135 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2136 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2137
2138 // Multiply by the element size and add to the base.
2139 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2140 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2141 }
2142 }
2143
2144 // Make sure that the offset fits in uintptr_t.
2145 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2146 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2147
2148 // Okay, we have now emitted all of the variable index parts to the BB that
2149 // the GEP is defined in. Loop over all of the using instructions, inserting
2150 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002151 // instruction to use the newly computed value, making GEPI dead. When the
2152 // user is a load or store instruction address, we emit the add into the user
2153 // block, otherwise we use a canonical version right next to the gep (these
2154 // won't be foldable as addresses, so we might as well share the computation).
2155
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002156 std::map<BasicBlock*,Value*> InsertedExprs;
2157 while (!GEPI->use_empty()) {
2158 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002159
2160 // If this use is not foldable into the addressing mode, use a version
2161 // emitted in the GEP block.
2162 Value *NewVal;
2163 if (!isa<LoadInst>(User) &&
2164 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2165 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2166 Ptr, PtrOffset);
2167 } else {
2168 // Otherwise, insert the code in the User's block so it can be folded into
2169 // any users in that block.
2170 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002171 User->getParent(), GEPI,
2172 Ptr, PtrOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002173 }
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002174 User->replaceUsesOfWith(GEPI, NewVal);
2175 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002176
2177 // Finally, the GEP is dead, remove it.
2178 GEPI->eraseFromParent();
2179}
2180
Chris Lattner1c08c712005-01-07 07:47:53 +00002181bool SelectionDAGISel::runOnFunction(Function &Fn) {
2182 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2183 RegMap = MF.getSSARegMap();
2184 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2185
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002186 // First, split all critical edges for PHI nodes with incoming values that are
2187 // constants, this way the load of the constant into a vreg will not be placed
2188 // into MBBs that are used some other way.
2189 //
2190 // In this pass we also look for GEP instructions that are used across basic
2191 // blocks and rewrites them to improve basic-block-at-a-time selection.
2192 //
Chris Lattner36b708f2005-08-18 17:35:14 +00002193 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2194 PHINode *PN;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002195 BasicBlock::iterator BBI;
2196 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner36b708f2005-08-18 17:35:14 +00002197 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2198 if (isa<Constant>(PN->getIncomingValue(i)))
2199 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002200
2201 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2202 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2203 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner36b708f2005-08-18 17:35:14 +00002204 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002205
Chris Lattner1c08c712005-01-07 07:47:53 +00002206 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2207
2208 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2209 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00002210
Chris Lattner1c08c712005-01-07 07:47:53 +00002211 return true;
2212}
2213
2214
Chris Lattnerddb870b2005-01-13 17:59:43 +00002215SDOperand SelectionDAGISel::
2216CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002217 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00002218 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002219 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00002220 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002221
2222 // If this type is not legal, we must make sure to not create an invalid
2223 // register use.
2224 MVT::ValueType SrcVT = Op.getValueType();
2225 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2226 SelectionDAG &DAG = SDL.DAG;
2227 if (SrcVT == DestVT) {
2228 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2229 } else if (SrcVT < DestVT) {
2230 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00002231 if (MVT::isFloatingPoint(SrcVT))
2232 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2233 else
Chris Lattnerfab08872005-09-02 00:19:37 +00002234 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002235 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2236 } else {
2237 // The src value is expanded into multiple registers.
2238 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2239 Op, DAG.getConstant(0, MVT::i32));
2240 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2241 Op, DAG.getConstant(1, MVT::i32));
2242 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2243 return DAG.getCopyToReg(Op, Reg+1, Hi);
2244 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002245}
2246
Chris Lattner068a81e2005-01-17 17:15:02 +00002247void SelectionDAGISel::
2248LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2249 std::vector<SDOperand> &UnorderedChains) {
2250 // If this is the entry block, emit arguments.
2251 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00002252 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00002253 SDOperand OldRoot = SDL.DAG.getRoot();
2254 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00002255
Chris Lattnerbf209482005-10-30 19:42:35 +00002256 unsigned a = 0;
2257 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2258 AI != E; ++AI, ++a)
2259 if (!AI->use_empty()) {
2260 SDL.setValue(AI, Args[a]);
Chris Lattnerfa577022005-09-13 19:30:54 +00002261
Chris Lattnerbf209482005-10-30 19:42:35 +00002262 // If this argument is live outside of the entry block, insert a copy from
2263 // whereever we got it to the vreg that other BB's will reference it as.
2264 if (FuncInfo.ValueMap.count(AI)) {
2265 SDOperand Copy =
2266 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2267 UnorderedChains.push_back(Copy);
2268 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00002269 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002270
2271 // Next, if the function has live ins that need to be copied into vregs,
2272 // emit the copies now, into the top of the block.
2273 MachineFunction &MF = SDL.DAG.getMachineFunction();
2274 if (MF.livein_begin() != MF.livein_end()) {
2275 SSARegMap *RegMap = MF.getSSARegMap();
2276 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2277 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2278 E = MF.livein_end(); LI != E; ++LI)
2279 if (LI->second)
2280 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2281 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner068a81e2005-01-17 17:15:02 +00002282 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002283
2284 // Finally, if the target has anything special to do, allow it to do so.
2285 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00002286}
2287
2288
Chris Lattner1c08c712005-01-07 07:47:53 +00002289void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2290 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2291 FunctionLoweringInfo &FuncInfo) {
2292 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002293
2294 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002295
Chris Lattnerbf209482005-10-30 19:42:35 +00002296 // Lower any arguments needed in this block if this is the entry block.
2297 if (LLVMBB == &LLVMBB->getParent()->front())
2298 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00002299
2300 BB = FuncInfo.MBBMap[LLVMBB];
2301 SDL.setCurrentBasicBlock(BB);
2302
2303 // Lower all of the non-terminator instructions.
2304 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2305 I != E; ++I)
2306 SDL.visit(*I);
2307
2308 // Ensure that all instructions which are used outside of their defining
2309 // blocks are available as virtual registers.
2310 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002311 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00002312 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00002313 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00002314 UnorderedChains.push_back(
2315 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00002316 }
2317
2318 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2319 // ensure constants are generated when needed. Remember the virtual registers
2320 // that need to be added to the Machine PHI nodes as input. We cannot just
2321 // directly add them, because expansion might result in multiple MBB's for one
2322 // BB. As such, the start of the BB might correspond to a different MBB than
2323 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00002324 //
Chris Lattner1c08c712005-01-07 07:47:53 +00002325
2326 // Emit constants only once even if used by multiple PHI nodes.
2327 std::map<Constant*, unsigned> ConstantsOut;
2328
2329 // Check successor nodes PHI nodes that expect a constant to be available from
2330 // this block.
2331 TerminatorInst *TI = LLVMBB->getTerminator();
2332 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2333 BasicBlock *SuccBB = TI->getSuccessor(succ);
2334 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2335 PHINode *PN;
2336
2337 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2338 // nodes and Machine PHI nodes, but the incoming operands have not been
2339 // emitted yet.
2340 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00002341 (PN = dyn_cast<PHINode>(I)); ++I)
2342 if (!PN->use_empty()) {
2343 unsigned Reg;
2344 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2345 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2346 unsigned &RegOut = ConstantsOut[C];
2347 if (RegOut == 0) {
2348 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002349 UnorderedChains.push_back(
2350 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00002351 }
2352 Reg = RegOut;
2353 } else {
2354 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00002355 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00002356 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00002357 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2358 "Didn't codegen value into a register!??");
2359 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002360 UnorderedChains.push_back(
2361 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00002362 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002363 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002364
Chris Lattnerf44fd882005-01-07 21:34:19 +00002365 // Remember that this register needs to added to the machine PHI node as
2366 // the input for this MBB.
2367 unsigned NumElements =
2368 TLI.getNumElements(TLI.getValueType(PN->getType()));
2369 for (unsigned i = 0, e = NumElements; i != e; ++i)
2370 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00002371 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002372 }
2373 ConstantsOut.clear();
2374
Chris Lattnerddb870b2005-01-13 17:59:43 +00002375 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00002376 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00002377 SDOperand Root = SDL.getRoot();
2378 if (Root.getOpcode() != ISD::EntryToken) {
2379 unsigned i = 0, e = UnorderedChains.size();
2380 for (; i != e; ++i) {
2381 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2382 if (UnorderedChains[i].Val->getOperand(0) == Root)
2383 break; // Don't add the root if we already indirectly depend on it.
2384 }
2385
2386 if (i == e)
2387 UnorderedChains.push_back(Root);
2388 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00002389 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2390 }
2391
Chris Lattner1c08c712005-01-07 07:47:53 +00002392 // Lower the terminator after the copies are emitted.
2393 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00002394
2395 // Make sure the root of the DAG is up-to-date.
2396 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00002397}
2398
2399void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2400 FunctionLoweringInfo &FuncInfo) {
Jim Laskeyb2efb852006-01-04 22:28:25 +00002401 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner1c08c712005-01-07 07:47:53 +00002402 CurDAG = &DAG;
2403 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2404
2405 // First step, lower LLVM code to some DAG. This DAG may use operations and
2406 // types that are not supported by the target.
2407 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2408
Chris Lattneraf21d552005-10-10 16:47:10 +00002409 // Run the DAG combiner in pre-legalize mode.
2410 DAG.Combine(false);
Nate Begeman2300f552005-09-07 00:15:36 +00002411
Chris Lattner1c08c712005-01-07 07:47:53 +00002412 DEBUG(std::cerr << "Lowered selection DAG:\n");
2413 DEBUG(DAG.dump());
2414
2415 // Second step, hack on the DAG until it only uses operations and types that
2416 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00002417 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00002418
2419 DEBUG(std::cerr << "Legalized selection DAG:\n");
2420 DEBUG(DAG.dump());
2421
Chris Lattneraf21d552005-10-10 16:47:10 +00002422 // Run the DAG combiner in post-legalize mode.
2423 DAG.Combine(true);
Nate Begeman2300f552005-09-07 00:15:36 +00002424
Evan Chenga9c20912006-01-21 02:32:06 +00002425 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattnerd48050a2005-10-05 06:09:10 +00002426
Chris Lattnera33ef482005-03-30 01:10:47 +00002427 // Third, instruction select all of the operations to machine code, adding the
2428 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00002429 InstructionSelectBasicBlock(DAG);
2430
Chris Lattner1c08c712005-01-07 07:47:53 +00002431 DEBUG(std::cerr << "Selected machine code:\n");
2432 DEBUG(BB->dump());
2433
Chris Lattnera33ef482005-03-30 01:10:47 +00002434 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00002435 // PHI nodes in successors.
2436 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2437 MachineInstr *PHI = PHINodesToUpdate[i].first;
2438 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2439 "This is not a machine PHI node that we are updating!");
2440 PHI->addRegOperand(PHINodesToUpdate[i].second);
2441 PHI->addMachineBasicBlockOperand(BB);
2442 }
Chris Lattnera33ef482005-03-30 01:10:47 +00002443
2444 // Finally, add the CFG edges from the last selected MBB to the successor
2445 // MBBs.
2446 TerminatorInst *TI = LLVMBB->getTerminator();
2447 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2448 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2449 BB->addSuccessor(Succ0MBB);
2450 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002451}
Evan Chenga9c20912006-01-21 02:32:06 +00002452
2453//===----------------------------------------------------------------------===//
2454/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2455/// target node in the graph.
2456void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2457 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00002458 ScheduleDAG *SL = NULL;
2459
2460 switch (ISHeuristic) {
2461 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Cheng3f239522006-01-25 09:12:57 +00002462 case defaultScheduling:
2463 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2464 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2465 else /* TargetLowering::SchedulingForRegPressure */
2466 SL = createBURRListDAGScheduler(DAG, BB);
2467 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002468 case noScheduling:
2469 case simpleScheduling:
2470 case simpleNoItinScheduling:
2471 SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
2472 break;
Evan Chengf0f9c902006-01-23 08:26:10 +00002473 case listSchedulingBURR:
2474 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattnera5de4842006-03-05 21:10:33 +00002475 break;
Chris Lattner03fc53c2006-03-06 00:22:00 +00002476 case listSchedulingTD:
2477 SL = createTDListDAGScheduler(DAG, BB, GetTargetHazardRecognizer());
Chris Lattnera5de4842006-03-05 21:10:33 +00002478 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002479 }
Chris Lattnera3818e62006-01-21 19:12:11 +00002480 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00002481 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00002482}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00002483
Chris Lattner03fc53c2006-03-06 00:22:00 +00002484HazardRecognizer &SelectionDAGISel::
2485GetTargetHazardRecognizer() {
2486 static HazardRecognizer DefaultRecognizer;
2487 return DefaultRecognizer;
2488}
2489
Chris Lattner0e43f2b2006-02-24 02:13:54 +00002490/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2491/// by tblgen. Others should not call it.
2492void SelectionDAGISel::
2493SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2494 std::vector<SDOperand> InOps;
2495 std::swap(InOps, Ops);
2496
2497 Ops.push_back(InOps[0]); // input chain.
2498 Ops.push_back(InOps[1]); // input asm string.
2499
2500 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2501 unsigned i = 2, e = InOps.size();
2502 if (InOps[e-1].getValueType() == MVT::Flag)
2503 --e; // Don't process a flag operand if it is here.
2504
2505 while (i != e) {
2506 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2507 if ((Flags & 7) != 4 /*MEM*/) {
2508 // Just skip over this operand, copying the operands verbatim.
2509 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2510 i += (Flags >> 3) + 1;
2511 } else {
2512 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2513 // Otherwise, this is a memory operand. Ask the target to select it.
2514 std::vector<SDOperand> SelOps;
2515 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2516 std::cerr << "Could not match memory address. Inline asm failure!\n";
2517 exit(1);
2518 }
2519
2520 // Add this to the output node.
2521 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2522 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2523 i += 2;
2524 }
2525 }
2526
2527 // Add the flag input back if present.
2528 if (e != InOps.size())
2529 Ops.push_back(InOps.back());
2530}